简体   繁体   中英

Python - class object attribute setter not working

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

The setter needs 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM