You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Polar类幂运算异常:返回对象地址而非预期格式化结果

问题分析

实现极坐标polar类时遇到两个问题:

  • 当指数在0到1之间时,返回的列表打印的是对象内存地址而非格式化字符串
  • 曾尝试用yield实现多结果返回,但循环变量i不递增,只能获取第一个结果

预期结果

[3.0 54.0º, 3.0 126.0º, 3.0 198.0º, 3.0 270.0º, 3.0 342.0º]

实际结果

[<__main__.polar object at 0x00000198710D66D0>, <__main__.polar object at 0x00000198710D6690>, <__main__.polar object at 0x00000198710D68D0>, <__main__.polar object at 0x00000198710D65D0>, <__main__.polar object at 0x00000198710D6850>]
解决方案

1. 解决对象地址打印问题

Python打印列表中的对象时,默认调用__repr__方法而非__str__。只需给polar类添加__repr__方法,让它返回和__str__一致的格式化字符串即可:

def __repr__(self) -> str:
    return self.__str__()

2. 修正yield实现问题(可选)

如果想用yield返回多结果,需将__pow__改为生成器函数,调用时要转成列表才能打印所有结果:

def __pow__(self, exponent):
    if type(exponent) not in (int, float):
        raise TypeError("Exponent must be a number")
    if exponent == 0:
        yield polar(1, 0)
    elif exponent == 1:
        yield self
    elif exponent > 1 or exponent < 0:
        yield polar(self.r**exponent, self.alpha*exponent)
    else:
        index = int(1/exponent)
        for i in range(index):
            alpha = (self.alpha/index) + ((360/index)*i)
            yield polar(self.r**exponent, alpha)

调用方式:print(list(polar(0-243j)**(1/5)))

3. 修复初始化方法的逻辑错误

原__init__中处理实部为0的逻辑有误,应判断虚部正负来确定角度:

else:
    if complex_num.imag > 0:
        self.alpha = 90
    else:
        self.alpha = 270
完整修正后的代码
import math

def sin(x,/):
    return math.sin(math.radians(x))

def cos(x,/):
    return math.cos(math.radians(x))

def arctan(x,/):
    return math.degrees(math.atan(x))


class polar():
    def __init__(self, complex_num,angle=None):
        if angle != None:
            self.r = complex_num
            self.alpha = angle
        elif type(complex_num) in (float, int, complex):
            complex_num = complex(complex_num)
            self.r = ((complex_num.real**2)+(complex_num.imag**2))**0.5
            if complex_num.real != 0:
                if complex_num.imag > 0 and complex_num.real > 0:
                    self.alpha = arctan(complex_num.imag/complex_num.real)
                elif complex_num.imag > 0 and complex_num.real < 0:
                    self.alpha = 180-(arctan(complex_num.imag/abs(complex_num.real)))
                elif complex_num.imag < 0 and complex_num.real < 0:
                    self.alpha = 180+(arctan(abs(complex_num.imag)/abs(complex_num.real)))
                else:
                    self.alpha = 360-(arctan(abs(complex_num.imag)/complex_num.real))
            else:
                if complex_num.imag > 0:
                    self.alpha = 90
                else:
                    self.alpha = 270
        while self.alpha >= 360:
            self.alpha -=360
        while self.alpha < 0:
            self.alpha += 360
            
    def __pow__(self,exponent):
        result = []
        if type(exponent) not in (int,float):
            raise TypeError("Exponent must be a number")
        if exponent == 0:
            return polar(1,0)
        elif exponent == 1:
            return self
        elif exponent > 1 or exponent < 0:
            return polar(self.r**exponent, self.alpha*exponent)
        else:
            index = int(1/exponent)
            for i in range(index):
                alpha = (self.alpha/index) + ((360/index)*i)
                result.append(polar(self.r**exponent, alpha))
            return result
                
    def __str__(self) -> str:
        return f"{self.r} {self.alpha}º"
    
    def __repr__(self) -> str:
        return self.__str__()
    
    @staticmethod
    def complexToPolar(polar_num: str,/):
        try:
            polar_num = polar_num.replace("º","").split()
            r = float(polar_num[0])
            alpha = float(polar_num[1])
            z = r*(cos(alpha)+sin(alpha)*1j)
            return z
        except:
            raise TypeError("Invalid polar string format")

print(polar(0-243j)**(1/5))
运行结果
[3.0 54.0º, 3.0 126.0º, 3.0 198.0º, 3.0 270.0º, 3.0 342.0º]

内容的提问来源于stack exchange,提问作者BerniusIII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:58:24