4

我有一个“class1”,它必须能够创建一个不同类名的对象。类名作为称为“朋友”的参数传递。我希望“朋友”参数默认为名为“class2”的类名。

此外,我需要对“class2”类具有相同的行为。所以“class2”应该有“class1”作为默认的朋友参数:

class class1():
 def __init__(self, friend = class2):
  self.friendInstance = friend()

class class2():
 def __init__(self, friend = class1):
  self.friendInstance = friend()

class1()
class2()

现在我收到以下错误消息:

    def __init__(self, friend = class2):
NameError: name 'class2' is not defined

当然,我不能在 class1 之前定义 class2,因为这会导致类似的错误:“class1”未定义。你知道解决办法吗?

非常感谢你的帮助!

亨利

4

2 回答 2

3

您可以将其推送到以后:

class class1(object):
    def __init__(self, friend=None):
        if friend is None:
            friend = class2
        self.friendInstance = friend()

编辑:实际上,不要那样做。它将创建一个 class2 实例,该实例创建一个 class1 实例,该实例创建一个 class2 实例等。也许您真的想传递一个实例而不是要实例化的类:

class class1(object):
    def __init__(self, friend=None):
        if friend is None:
            self.friendInstance = class2(self)
        else:
            self.friendInstance = friend

对于class2也是如此。这不是那么灵活,但它非常简单。如果你真的想要灵活性,你可以这样做:

class class1(object):
    def __init__(self, friend=None, friendClass=None):
        if friend is None:
            self.friendInstance = (class2 if friendClass is None else friendClass)(self)
        else:
            self.friendInstance = friend

class class2(object):
    def __init__(self, friend=None, friendClass=class1):
        if friend is None:
            self.friendInstance = friendClass(self)
        else:
            self.friendInstance = friend

这可以通过继承或元类来简化,但你可能明白了。

于 2011-01-10T15:33:39.953 回答
1

即使您解决了NameError,您也会遇到另一个问题 - 即您正在尝试创建递归数据结构。每个实例都class1尝试创建的实例class2,它同样尝试创建另一个class1实例,等等,等等,无穷无尽(实际上只有在你得到 a 之前RuntimeError: maximum recursion depth exceeded)。

在不了解您实际尝试做的事情的情况下,这是一个简单的解决方案:

class class1(object):
    def __init__(self, friend=None):
        if friend is None:
            friend = class2(self) # create a class2 instance with myself as a friend
        self.friendInstance = friend

class class2(object):
    def __init__(self, friend=None):
        if friend is None:
            friend = class1(self) # create a class1 instance with myself as a friend
        self.friendInstance = friend

print class1()
# <__main__.class1 object at 0x00B42450>
print class2()
# <__main__.class2 object at 0x00B65530>
于 2011-01-10T17:02:50.213 回答