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()
现在我收到以下错误消息:
def __init__(self, friend = class2):
NameError: name 'class2' is not defined
当然,我不能在 class1 之前定义 class2 因为 这会导致类似的错误:“class1”未定义。 你知道解决办法吗?
非常感谢您的帮助!
亨利
I have a "class1" which must be able to create an object of a
different class-name. The class-name is passed as an argument called "friend".
I want the "friend"-argument to default to a class-name called "class2".
Additionally I need to have the same behavior for the class "class2".
So "class2" should have "class1" as a default friend-argument:
class class1():
def __init__(self, friend = class2):
self.friendInstance = friend()
class class2():
def __init__(self, friend = class1):
self.friendInstance = friend()
class1()
class2()
Now i get the following error-message:
def __init__(self, friend = class2):
NameError: name 'class2' is not defined
Of course, i can't define class2 before class1 because
this would result in a similar error: "class1" is not defined.
Do you know a solution?
Thanks a lot for your help!
Henry
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将其推到稍后:
编辑:实际上,不要这样做。它将创建一个 class2 实例,该实例创建一个 class1 实例,该实例创建一个 class2 实例,等等。也许您确实想传递一个实例而不是要实例化的类:
对于 class2 也是如此。虽然不太灵活,但非常简单。如果你真的想要灵活性,你可以这样做:
这可以通过继承或元类来简化,但你可能明白了。
You can push it to later:
Edit: Actually, don't do that. It will create a class2 instance that creates a class1 instance that creates a class2 instance, etc. Maybe you really want to pass an instance in instead of the class to be instantiated:
and likewise for class2. That isn't as flexible, but it's pretty simple. If you really want flexibility, you can do something like this:
That could be simplified with inheritance or metaclasses, but you probably get the idea.
即使您解决了
NameError
,您也会遇到另一个问题——即您试图创建递归数据结构。class1
的每个实例都尝试<em>创建一个class2
的实例,该实例同样尝试创建另一个class1
实例,等等,无限循环(实际上只有到你得到一个RuntimeError:超出最大递归深度
)。在不了解您实际想要做什么的情况下,这里有一个简单的解决方案:
Even if you solve the
NameError
, you'll run into another -- namely that you've attempting to create a recursive data-structure. Each instance ofclass1
attempts to create an instance ofclass2
, which likewise attempts to create anotherclass1
instance, etc, etc, ad infinitum (actually only until you get aRuntimeError: maximum recursion depth exceeded
).Without knowing a little more about what you're actually trying to do, here's one simple solution: