在Python中的同一类定义中创建类的实例
我正在尝试在 MyClass 的定义中创建一个新的 MyClass 实例。
为什么这段代码会失败以及如何实现它?
class MyClass:
def __init__(self):
self.child=MyClass()
mc=MyClass()
I am trying to create a new MyClass instance in MyClass's definition.
Why does this code fail and how can achieve it?
class MyClass:
def __init__(self):
self.child=MyClass()
mc=MyClass()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,它失败了,因为它有无限递归。想想看,如果每个 MyClass 都有一个子类,它也是 MyClass,那么它会无限延续下去!
您可以通过几种方式解决这个问题。首先,您可以为构造函数提供一个参数:
或者,您可以使用另一个外部方法:
我个人更喜欢第一个解决方案,因为这意味着外部对象不需要了解有关该类的任何信息。当然,您可以将两者结合起来:
这样 mc 默认情况下有一个子级,您可以选择随时设置子级。
还有一种“让我们创建一定数量”的方法:
旁白:如果你想获取一个对象的类,你可以使用值
obj.__class__
。这将在上面的所有示例中输出 MyClass。Well, it fails because it has infinite recursion. Think about it, if every MyClass has a child which is a MyClass, it will go on for infinity!
You can resolve this a couple of ways. First, you can have a parameter to the constructor:
Or, you can have another, external method:
I personally prefer the first solution as it means that outside objects don't need to know anything about the class. Of course, you could combine the two:
This way mc has a child by default and you have the option of setting the child whenever you like.
Then there is also the "let's create a certain number" approach:
Aside: If you want to get an object's class, you can use the value
obj.__class__
. That will output MyClass in all of the examples above.您正在进行无限递归调用 -
MyClass
在初始化期间创建另一个MyClass
,因此它会无限递归。您可能想做一些类似的事情:
如果您感觉特别顽皮,您可以尝试:
You're making an infinitely recursing call —
MyClass
is creating anotherMyClass
during initialization, and thus it recurses infinitely.You may want to do something like:
If you're feeling particularly naughty, you could try:
你所做的实际上是递归的,MyClass 的新实例将创建一个新实例,该实例又将创建一个新实例,等等......
Soo,我想这就是您的代码失败的原因,因为您没有发布错误消息,所以我无法确定。
What you did there is actualy recursive, the new isntance of MyClass will create a new instance that will in turn create a new one, etc ...
Soo I supose that is why your code fails, I can't tell for sure since you didn't post the error message.
我建议定义两个类:
我认为如果两个类必须以两种不同的方式表现,那么它们一定是不同的(尽管一个类可以对另一个类进行子类化)
I suggest to define two classes:
I think that if two classes must behave in two different ways, they must be different (although one can subclass the other)