简体   繁体   English

使用属性装饰器的 python class 中的属性行为

[英]Attribute behaviour in python class using property decorator

I'm confused with how attribute variables are behaving in my class when using the property decorator.使用属性装饰器时,我对属性变量在 class 中的行为方式感到困惑。

See this example:看这个例子:

class Example:
  def __init__(self, x):
    self.x = x

  @property
  def x(self):
    return self.__x

  @x.setter
  def x(self, x):
    self.__x = x

This works fine, but how?这工作正常,但如何? The variable inside the setter property ( self.__x ) has not been "defined" in the constructor, so how can it be assigned a value? setter 属性( self.__x )中的变量尚未在构造函数中“定义”,那么如何为其赋值?

Other stuff also works, for example, take the same class defined above and add a new member function to it:其他东西也可以,例如,采用上面定义的相同 class 并添加一个新成员 function 到它:

  def set_val_x(self):
    self.__x = 8765

Again, using this function actually works, similar to the property.setter (but it's not using the property decorator).同样,使用这个 function 确实有效,类似于 property.setter (但它不使用属性装饰器)。

In Python, you don't have to define variables in the constructor.在 Python 中,您不必在构造函数中定义变量。 You can assign them whenever you want.您可以随时分配它们。

class Foo:
    def __init__(self, bar):
        self.bar = bar
my_foo = Foo(3)
my_foo.other_thing = 6

is perfectly legal, for example.例如,是完全合法的。

Inside __init__ , the line__init__内,行

self.x = x

is no longer short for不再是缩写

setattr(self, 'x', x)

because the class attribute Example.x exists.因为 class 属性Example.x存在。 You are no longer creating an instance attribute x , but calling您不再创建实例属性x ,而是调用

type(self).X.__set__(self, 'x', x)

which will set the instance attribute __x .这将设置实例属性__x

Instance attributes can be created, modified, or deleted at any time.可以随时创建、修改或删除实例属性。 The __init__ method is just a convenient, single place to create them because it is called for you automatically every time you create an instance. __init__方法只是一个方便的、单一的创建它们的地方,因为每次创建实例时都会自动调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM