[PYTHON] When using property, use a class that inherits object (new-style class)

If not new-style class

class Hoge:
    def __init__(self):
        self._x = 1

    @property
    def x(self):
        print 'property', self._x
        return self._x

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

a = Hoge()
print a.x

a.x = 2
print a.x

result##

property 1
1
2

For new-style class

class Hoge(object):
    def __init__(self):
        self._x = 1

    @property
    def x(self):
        print 'property', self._x
        return self._x

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

a = Hoge()
print a.x

a.x = 2
print a.x

result##

property 1
1
setter
property 2
2

reference##

Recommended Posts

When using property, use a class that inherits object (new-style class)
Use a Property Decorator?
A story that stumbled when using pip in a proxy environment
Use a macro that runs when saving python with vscode
Use configparser when using API
I got a TypeError:'int' object is not iterable when using keras
The story that a hash error came out when using Pipenv
A memorandum until using mecab on a machine that cannot use sudo
I get a can't set attribute when using @property in python
A memorandum when using beautiful soup
[Note] Significance that __unicode__ is necessary when defining a Django model class
Knowledge when making a bot using discord.py
A program that plays rock-paper-scissors using Python