1

I have created a class that has a property with a setter. There are 2 different ways to use this class, so the values of some of the object components may be set in a different order depending on the scenario (i.e. I don't want to set them during __init__). I have included a non-property with its own set function here to illustrate what is and isn't working.

class Dumbclass(object):

  def __init__(self):
    self.name = None
    self.__priority = None

  @property
  def priority(self):
    return self.__priority

  @priority.setter
  def priority(self, p):
    self.__priority = p

  def set_name(self, name):
    self.name = "dumb " + name

  def all_the_things(self, name, priority=100):
    self.set_name(name) 
    self.priority(priority)

    print self.name
    print self.priority

When I run the following, it returns TypeError: 'NoneType' object is not callable. I investigated with pdb, and found that it was calling the getter instead of the setter at self.priority(priority).

if __name__ == '__main__':
  d1 = Dumbclass()
  d1.all_the_things("class 1")

  d2 = Dumbclass()
  d2.all_the_things("class 2", 4)

What's going on here?

kimash
  • 13
  • 4

2 Answers2

3

Short Answer: Please change your line self.priority(priority) to self.priority = priority

Explanation: Setter is called only when you assign something to the attribute. In your code, you are not doing an assignment operation.

Here are some nice references if you want to understand more:

  1. Python descriptors
  2. How does the @property decorator work?
  3. Real Life Example
Community
  • 1
  • 1
Jose Cherian
  • 7,207
  • 3
  • 36
  • 39
  • Can you provide a good example of why one would want to bother with making a separate setter at all? – kimash Oct 10 '16 at 21:27
2

You are facing this issue due to trying to treat priority as a method in your all_the_things method. At this point it is already a property, so you assign to it like a variable:

def all_the_things(self, name, priority=100):
    self.set_name(name)
    self.priority = priority
jaypb
  • 1,544
  • 10
  • 23