0

I noticed that if you have a property in your class with a setter function, it won't work unless you subclass something. Here's an example:

This does not print anything to the output, and does not set the value

class MyClass():
    def __init__(self):
        self.tax = 3

    @property
    def cost(self):
        self._cost = 15
        return self._cost - self.tax

    @cost.setter
    def cost(self, value):
        self._cost = value
        print "New Cost: {}".format(self._cost - self.tax)

mycls = MyClass()
mycls.cost = 55

But if I subclass object, it works fine:



class MyClass(object):
    def __init__(self):
        self.tax = 3

    @property
    def cost(self):
        self._cost = 15
        return self._cost - self.tax

    @cost.setter
    def cost(self, value):
        self._cost = value
        print "New Cost: {}".format(self._cost - self.tax)

mycls = MyClass()
mycls.cost = 55
>>> New Cost: 52

Why exactly is this? And what is object?

  • 2
    These two pieces of code look exactly the same... Copy & paste mistake? – ForceBru Mar 05 '20 at 18:49
  • 1
    Did you mean to subclass `object` in your first code snippet? – MattDMo Mar 05 '20 at 18:49
  • 3
    This is only in Python2, in Python 3, all classes are inherited from Object automatically. – aminrd Mar 05 '20 at 18:50
  • Does this question and its answers help you understand what's going on here: https://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python – Blckknght Mar 05 '20 at 18:54
  • https://docs.python.org/3/tutorial/classes.html – wwii Mar 05 '20 at 20:08
  • If you are using Python 2, you really shouldn't be unless you have a very good reason... (like maintaining an old code base). – juanpa.arrivillaga Mar 06 '20 at 01:30
  • Sorry about that! Edited code. Thanks for sharing the links, that helps explain it better :) –  Mar 06 '20 at 07:57

0 Answers0