【问题标题】:Do we have to always use self.variable while using them in some expression? [duplicate]在某些表达式中使用它们时,我们是否必须始终使用 self.variable? [复制]
【发布时间】:2023-03-18 16:31:01
【问题描述】:
class learn:

    def __init__(self,radius=1):
        self.radius = radius
     
    def reset_area(self,new_radius):
        self.radius= new_radius
        self.area = new_radius*new_radius*3.14
        self.circum = 2*3.14*radius
        return area + circum  

错误 - "circum" is not defined. - "area" is not defined.

【问题讨论】:

  • 在类方法中引用类成员时,是的 - 您始终需要将它们指定为 self.something
  • 是的。您需要将self 作为前缀。
  • 这就是为什么您需要发布minimal reproducible example

标签: python self


【解决方案1】:

当您使用self.variable = 'sth' 设置变量时,该变量将设置为类属性并且可以在整个类中访问

但是当您使用variable = 'sth' 时,它不再是类属性,只能在该函数中访问

如果您不想将areacircum 作为类属性,请不要使用self

...
area = new_radius*new_radius*3.14
circum = 2*3.14*new_radius
return area + circum

但是如果你想让它们在这个方法之外,是的,你应该使用self

【讨论】:

    【解决方案2】:

    你还没有声明一个名为circum的变量,所以是的,在这种情况下,你必须引用你创建的变量,这里的名字是self.circum

    您的代码在对象实例中创建了两个新属性,这可能不是您想要的;所以在这种情况下,从areacircum 中删除self. 前缀可能会更接近你真正想要的(假设你没有其他假设这些属性存在的方法;但是你的@987654326 @ 方法可能应该使用一些默认值来创建它们,例如 None)。

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 2017-11-05
      • 2015-06-08
      • 2017-08-29
      • 2017-02-12
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      相关资源
      最近更新 更多