Python 中 类 方法之间的循环引用
Circular referencing between methods of classes in Python
我的代码有两个 class 以下列方式相互依赖。
class Shepherd:
def __init__(self, name='Bob', address='Shepherd Way 1', sheep=[]):
self.name=name
self.address=address
self.sheep=sheep # a list of objects of the class Sheep
class Sheep:
def __init__(self, shepherd=Shepherd(), address=None, color='brown'):
self.color=color
# a sheep inherits the shepherd's address
self.address=shepherd.address
# and it gets added to the shepherd's list of sheep
shepherd.sheep = shepherd.sheep + [self]
def set_color(self, color='white'):
self.color=color
我现在想给 Shepherd class 添加一个方法 set_sheep_color()
。此方法应该对牧羊人拥有的每只羊使用方法 set_color
。问题是我不能那样做,因为 set_color
在 Shepherd class 之后定义。但是,我不能将 Sheep class 的定义移到 Shepherd class 之前,因为我在 Sheep class 中使用 Shepherd()
。如何在定义后将 set_sheep_color()
添加到 Shepherd class?或者有更好的方法来解决这个问题吗?
class Shepherd:
...
def set_sheep_color(self, color):
for s in self.sheep:
s.set_color(color)
在实际执行代码行之前,不会检查附加到对象的名称。在定义 Sheep class 之前 定义 这并不重要;重要的是你是否 运行 是 运行 绵羊 class。你显然已经完成了,因为你已经用一些必须已经存在的羊初始化了 Shepherd。
换句话说,当 python 查看附加到对象的变量和方法时,它会查看对象 当前存在的情况 - 而不是对象的规范.
我的代码有两个 class 以下列方式相互依赖。
class Shepherd:
def __init__(self, name='Bob', address='Shepherd Way 1', sheep=[]):
self.name=name
self.address=address
self.sheep=sheep # a list of objects of the class Sheep
class Sheep:
def __init__(self, shepherd=Shepherd(), address=None, color='brown'):
self.color=color
# a sheep inherits the shepherd's address
self.address=shepherd.address
# and it gets added to the shepherd's list of sheep
shepherd.sheep = shepherd.sheep + [self]
def set_color(self, color='white'):
self.color=color
我现在想给 Shepherd class 添加一个方法 set_sheep_color()
。此方法应该对牧羊人拥有的每只羊使用方法 set_color
。问题是我不能那样做,因为 set_color
在 Shepherd class 之后定义。但是,我不能将 Sheep class 的定义移到 Shepherd class 之前,因为我在 Sheep class 中使用 Shepherd()
。如何在定义后将 set_sheep_color()
添加到 Shepherd class?或者有更好的方法来解决这个问题吗?
class Shepherd:
...
def set_sheep_color(self, color):
for s in self.sheep:
s.set_color(color)
在实际执行代码行之前,不会检查附加到对象的名称。在定义 Sheep class 之前 定义 这并不重要;重要的是你是否 运行 是 运行 绵羊 class。你显然已经完成了,因为你已经用一些必须已经存在的羊初始化了 Shepherd。
换句话说,当 python 查看附加到对象的变量和方法时,它会查看对象 当前存在的情况 - 而不是对象的规范.