[英]Passing class instance reference to functions called in class definition in Python
[英]Give a reference to a python instance attribute at class definition
我有一个带有属性的类,该类具有对该类另一个属性的引用。 请参阅类Device
, value1
和value2
包含对interface
的引用:
class Interface(object):
def __init__(self):
self.port=None
class Value(object):
def __init__(self, interface, name):
self.interface=interface
self.name=name
def get(self):
return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port)
class Device(object):
interface=Interface()
value1=Value(interface, name="value1")
value2=Value(interface, name="value2")
def __init__(self, port):
self.interface.port=port
if __name__=="__main__":
d1=Device("Foo")
print d1.value1.get() # >>> Getting Value "value1" with interface "Foo"
d2=Device("Bar")
print d2.value1.get() # >>> Getting Value "value1" with interface "Bar"
print d1.value1.get() # >>> Getting Value "value1" with interface "Bar"
上次打印错误,原因是d1
应该具有接口“ Foo”。 我知道出了什么问题:解析类定义(一次)后,将执行line interface=Interface()
行。 因此,每个Device
类都具有相同的interface
实例。
我可以将Device
类更改为:
class Device(object):
interface=Interface()
value1=Value(interface, name="value1")
value2=Value(interface, name="value2")
def __init__(self, port):
self.interface=Interface()
self.interface.port=port
所以这也不起作用:这些值仍然引用原始接口实例,而self.interface只是另一个实例...
现在的输出是:
>>> Getting Value "value1" with interface "None"
>>> Getting Value "value1" with interface "None"
>>> Getting Value "value1" with interface "None"
那么我该如何用pythonic方法解决呢? 我可以在Device
类中设置一个函数来查找类型为Value
属性,然后为它们重新分配新接口。 这不是典型解决方案的普遍问题吗?
谢谢!
interface
是一个类属性。 所以当你这样做
d2=Device("Bar")
您正在更改Device
类的所有对象的interface
端口。
如果要每个对象实例具有这些属性,则必须将它们放入__init__
方法中:
class Device(object):
def __init__(self, port):
self.interface=Interface()
self.value1=Value(self.interface, name="value1")
self.value2=Value(self.interface, name="value2")
self.interface.port=port
仅当您确实想与所有对象共享值时,才应使用类属性。
除此之外,我不知道您想在这里完成什么。 为什么首先将其定义为类属性?
除非您的值是Device的方法,否则您不能推迟接口查找。 也许这样的事情可以满足您的需求?
def value(name):
def get(self):
print 'Getting %s from port %s' % (name, self.interface.port)
def set(self, v):
print 'Setting %s to %s on port %s' % (name, v, self.interface.port)
return property(get, set)
class Device(object):
value1 = value('value1')
value2 = value('value2')
def __init__(self, interface):
self.interface = interface
class Interface(object):
def __init__(self, port):
self.port = port
d = Device(Interface(1234))
d.value1
d.value2 = 42
如果您想让您的价值观做得比获取和设置更多,那就更困难了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.