【问题标题】:AttributeError: 'NoneType' object has no attribute 'magnitude'AttributeError:“NoneType”对象没有属性“大小”
【发布时间】:2026-01-22 01:40:01
【问题描述】:
class Force:
    def __init__(self,magnitude,angle):
        self.magnitude = magnitude
        self.angle = angle

    def get_horizontal(self):
        return self.magnitude * cos(radians(self.angle))

    def get_vertical(self):
        return self.magnitude * sin(radians(self.angle))

    def get_angle(self,use_degrees = True):
        if use_degrees:
            return self.angle
        else:
            return radians(self.angle)

def find_net_force(forces):
        tot_hor = 0
        tot_ver = 0
        for i in forces:
            tot_hor += i.get_horizontal()
            tot_ver += i.get_vertical()

        magnitude = (tot_hor ** 2 + tot_ver ** 2) ** 0.5
        magnitude = round(magnitude,1)
        angle = degrees(atan2((tot_ver),(tot_hor)))
        angle = round(angle,1)

force_1 = Force(50, 90)
force_2 = Force(75, -90)
force_3 = Force(100, 0)
forces = [force_1, force_2, force_3]
net_force = find_net_force(forces)
print(net_force.magnitude)
print(nIt_force.get_angle())

当我执行这段代码时,我得到了,
打印(net_force.magnitude)
AttributeError:“NoneType”对象没有“大小”属性
在哪里寻找错误,因为我可以看到某些东西与幅度部分有关。

【问题讨论】:

    标签: python-3.x class


    【解决方案1】:

    它在底部:

    print(net_force.magnitude)
    

    the_force 为 null,因为 find_net_force 的返回值。

    你看到的异常应该有一个堆栈跟踪显示你的行号。

    【讨论】:

    • 当我添加 return magnitude 时,它会显示 AttributeError: 'float' object has no attribute 'magnitude' 。那么这是什么意思呢?
    • 您已经让find_net_force 返回一个float 值,用于存储在the_force 变量中。 net_force.magnitude 正在访问 net_force 变量的“magnitude”属性。 float 值没有 magnitude 属性。
    • 浮点值在某种意义上没有幅度属性? (在我的情况下, net_force 的幅度属性应该是一个浮点数)我返回的幅​​度部分是一个浮点数。那么应该怎么做呢?
    • the_force 变量?
    • Force 对象本身,self
    最近更新 更多