Python 将对象作为属性相互指定
我有两类对象,顶部和底部。我成对创建对象,并希望将它们彼此指定,以便在项目中引用其他对象的对应对象。有没有比我的示例代码更优雅的方法Python 将对象作为属性相互指定,python,Python,我有两类对象,顶部和底部。我成对创建对象,并希望将它们彼此指定,以便在项目中引用其他对象的对应对象。有没有比我的示例代码更优雅的方法 class Top: def __init__(self,bottom): self.bottom = bottom class Bottom: def __init__(self): self.top = None def set_top(self,top): self.top = top
class Top:
def __init__(self,bottom):
self.bottom = bottom
class Bottom:
def __init__(self):
self.top = None
def set_top(self,top):
self.top = top
Top_Bottom_List = []
for i in range(5):
Current_Bottom = Bottom()
Current_Top = Top(Current_Bottom)
Current_Bottom.set_top(Current_Top)
Top_Bottom_list.append((Current_Top,Current_Bottom))
我的问题是,我想同时创建两个类的实例,但显然必须首先定义其中一个类,否则另一个类将无法设置任何值。没有其他间接层无法解决的问题:
def create_pair():
b = Bottom()
t = Top(b)
b.top = t
return b, t
…
top_bottom_list = [create_pair() for _ in range(5)]
如果耦合为1:1,还可以更改构造函数:
class Top:
def __init__(self, bottom = None):
if bottom is not None:
bottom.top = self
self.bottom = bottom
class Bottom:
def __init__(self, top = None):
if top is not None:
top.bottom = self
self.top = top
并将其用作:
def create_pair():
b = Bottom(Top())
return b, b.top
…虽然我不确定我是否喜欢这段代码。没有什么是其他间接层无法解决的:
def create_pair():
b = Bottom()
t = Top(b)
b.top = t
return b, t
…
top_bottom_list = [create_pair() for _ in range(5)]
如果耦合为1:1,还可以更改构造函数:
class Top:
def __init__(self, bottom = None):
if bottom is not None:
bottom.top = self
self.bottom = bottom
class Bottom:
def __init__(self, top = None):
if top is not None:
top.bottom = self
self.top = top
并将其用作:
def create_pair():
b = Bottom(Top())
return b, b.top
…虽然我不确定我是否喜欢这段代码。我更喜欢一个解决方案,它不会给一个类一个“首选”状态而不是另一个
class Top:
def __init__(self, bottom=None):
self.bottom = bottom
class Bottom:
def __init__(self, top=None):
self.top = top
def link(t, b):
t.bottom = b
b.top = t
return t, b
top_bottom_list = [link(Top(), Bottom()) for _ in range(5)]
如果不能在实例化时立即将链接对象传递给其他对象,那么最初什么都不做,然后让一个附加函数处理在实例化后将两者配对的问题。另外一个函数也可以处理实例化
def make_pair():
t = Top()
b = Bottom()
return link(t, b)
top_bottom_list = [make_pair() for _ in range(5)]
我更喜欢一个解决方案,它不会给一个类一个“首选”的状态
class Top:
def __init__(self, bottom=None):
self.bottom = bottom
class Bottom:
def __init__(self, top=None):
self.top = top
def link(t, b):
t.bottom = b
b.top = t
return t, b
top_bottom_list = [link(Top(), Bottom()) for _ in range(5)]
如果不能在实例化时立即将链接对象传递给其他对象,那么最初什么都不做,然后让一个附加函数处理在实例化后将两者配对的问题。另外一个函数也可以处理实例化
def make_pair():
t = Top()
b = Bottom()
return link(t, b)
top_bottom_list = [make_pair() for _ in range(5)]
我强烈建议你阅读并坚持它,除非有充分的理由不这样做。特别是,由于定义之间没有分隔换行符,代码很难阅读。请注意,惯用Python不会定义
set\u top(self,top)
,而只是将任何b.set\u top(top)
替换为b.top=top
。如果你想以后有一个setter,你总是可以透明地添加一个属性
。我强烈建议你阅读并坚持它,除非有充分的理由不这样做。特别是,由于定义之间没有分隔换行符,代码很难阅读。请注意,惯用Python不会定义set\u top(self,top)
,而只是将任何b.set\u top(top)
替换为b.top=top
。如果您想准备以后使用setter,您可以始终透明地添加属性。