Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's property decorator does not work as expected

class Silly:
    @property
    def silly(self):
        "This is a silly property"
        print("You are getting silly")
        return self._silly

    @silly.setter
    def silly(self, value):
        print("You are making silly {}".format(value))
        self._silly = value

    @silly.deleter
    def silly(self):
        print("Whoah, you killed silly!")
        del self._silly

s = Silly()
s.silly = "funny"
value = s.silly
del s.silly

But it does not print "You are getting silly", "You are making silly funny",... as expected. Don't know why. Can you have me figure out, folks?

Thanks in advance!

like image 378
Locke Avatar asked Dec 05 '22 17:12

Locke


1 Answers

The property decorator only works with new-style classes (see also). Make Silly extend from object explicitly to make it a new-style class. (In Python 3, all classes are new-style classes)

class Silly(object):
    @property
    def silly(self):
        # ...
    # ...
like image 117
icktoofay Avatar answered Jan 06 '23 07:01

icktoofay