The behavior of @property is different between class definition and old and new styles

A memo about property

In the 2nd system [^ 1].

[^ 1]: In the 3rd series, it is unconditionally judged as a new style, so no trouble occurs even if you write the old style.

I'm writing something that isn't an old-style feature in the old-style, so it's 100% user-friendly.

foo.py


class New(object):
    def __init__(self):
        self._x = 10

    @property
    def x(self):
        return self._x * 2

    @x.setter
    def x(self, v):
        self._x = v

class Old():
    def __init__(self):
        self._x = 10

    @property
    def x(self):
        return self._x * 2

    @x.setter
    def x(self, v):
        self._x = v

if __name__ == '__main__':
    n = New()
    n.x = 10
    print ( n.x )

    o = Old()
    o.x = 10
    print ( o.x )

Both New and ʻOld are exactly the same except for the line of the class` declaration.

python


$ python foo.py
20
10

I researched various things [^ 2], but ↓ is the most intuitive

[^ 2]: Is there a Python version of Data :: Dumper or is there a B :: Deparse?

Change after main


if __name__ == '__main__':
    n = New()
    print (vars(n))
    n.x = 2
    print (vars(n))

    o = Old()
    print (vars(o))
    o.x = 2
    print (vars(o))

python


$ python foo.py
{'_x': 10}
{'_x': 2}
{'_x': 10}
{'x': 2, '_x': 10}

In short, Old

class Old():
    def __init__(self):
        self._x = 10

if __name__ == '__main__':
    o = Old()
    print (vars(o))
    o.x = 2
    print (vars(o))

Same thing as running.

Recommended Posts

The behavior of @property is different between class definition and old and new styles
The answer of "1/2" is different between python2 and 3
Indent behavior of json.dumps is different between python2 and python3
The timing when the value of the default argument is evaluated is different between Ruby and Python.
I investigated the behavior of the difference between hard links and symbolic links
What is the difference between `pip` and` conda`?
About the behavior of copy, deepcopy and numpy.copy
Summary of the differences between PHP and Python
About the difference between "==" and "is" in python
What is the difference between Unix and Linux?
Consideration of the difference between ROC curve and PR curve
Find out the location of Python class definition files.
What is the difference between usleep, nanosleep and clock_nanosleep?
Visualization of the connection between malware and the callback server
Why is the first argument of [Python] Class self?
pca.components_ of sklearn is the correlation coefficient between the principal component and the feature, and is called the factor loading.
What is the difference between a symbolic link and a hard link?
Reuse the behavior of the @property method by using a descriptor [16/100]
A rough summary of the differences between Windows and Linux
Is the lottery profitable? ~ LOTO7 and the law of large numbers ~