Python:将“notyetdefined”类名作为默认参数

2024-10-01 17:21:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“class1”,它必须能够创建一个 不同的类名。类名作为名为“friend”的参数传递。 我希望“friend”参数默认为名为“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()

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

^{pr2}$

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

非常感谢你的帮助!在

亨利


Tags: selffriend消息参数定义initdef错误
2条回答

您可以稍后将其推送到:

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

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

^{pr2}$

第二类也一样。这不是很灵活,但很简单。如果你真的想要灵活性,你可以这样做:

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

这可以通过继承或元类来简化,但您可能会明白这一点。在

即使您解决了NameError,也会遇到另一个问题,即您试图创建递归数据结构。class1的每个实例都试图创建一个class2的实例,它同样会无限地尝试创建另一个class1实例等,以此类推(实际上,直到您得到一个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>

相关问题 更多 >

    热门问题