2

I've got a simple class setup here. What I want to happen is the 'print message' to be printed when I set the attribute 'info' of the class object Truck.

Nothing appears to be happening when I set the info property c.info = "Great" I would expect it to print "this is being set"

# Classes
class Node(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Truck(Node):
    def __init__(self, name="", age=0):
        super(Truck, self).__init__(name=name, age=age)
        self.info = None

        @property
        def info(self):
            return self.info

        @info.setter
        def info(self):
            print "this is being set"


c = Truck()
c.info = "great"
print c.info
4
  • 7
    Your @properties are indented too far. Commented Dec 1, 2015 at 20:15
  • that doesn't appear to fix it Commented Dec 1, 2015 at 20:22
  • 4
    Edit the question to fix the indenting so we know not to worry about that any more. Commented Dec 1, 2015 at 20:28
  • "nothing appears to be happening"... your code raises a ValueError and that's an interesting bit of information to include in the question. Commented Dec 1, 2015 at 20:34

1 Answer 1

5

The setterneeds to take a value. Furthermore, store the data in self._info to avoid recursive calls to self.info().

class Node(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Truck(Node):
    def __init__(self, name="", age=0):
        super(Truck, self).__init__(name=name, age=age)
        self._info = None

    @property
    def info(self):
        return self._info

    @info.setter
    def info(self, value):
        # you likely want to it here
        self._info = value
        print("this is being set")


c = Truck()
c.info = "great"
print(c.info)

This prints:

this is being set
great
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.