我在这里设置了一个简单的课程。我想要发生的是'打印消息'在我设置属性' 信息'时打印类对象卡车。
设置info属性c.info = "Great"
时似乎没有发生任何事情
我希望它可以打印"这是设置"
# 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
答案 0 :(得分:4)
setter
需要value
。此外,将数据存储在self._info
中,以避免对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 is being set
great