Matheus Müller
Matheus Müller

Reputation: 33

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.

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?

Other stuff also works, for example, take the same class defined above and add a new member function to it:

  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).

Upvotes: 2

Views: 375

Answers (2)

chepner
chepner

Reputation: 530872

Inside __init__, the line

self.x = x

is no longer short for

setattr(self, 'x', x)

because the class attribute Example.x exists. You are no longer creating an instance attribute x, but calling

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

which will set the instance attribute __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.

Upvotes: 1

LeopardShark
LeopardShark

Reputation: 4416

In Python, you don’t have to define variables in the constructor. 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.

Upvotes: 1

Related Questions