在Python中的同一类定义中创建类的实例

发布于 2024-12-02 18:59:31 字数 191 浏览 2 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一个人的旅程 2024-12-09 18:59:31

好吧,它失败了,因为它有无限递归。想想看,如果每个 MyClass 都有一个子类,它也是 MyClass,那么它会无限延续下去!

您可以通过几种方式解决这个问题。首先,您可以为构造函数提供一个参数:

class MyClass:
   def __init__(self, create = True):
      if create:
         self.child = MyClass(False)

mc = MyClass()

或者,您可以使用另一个外部方法:

class MyClass:
    def set_child(self,child = None):
        # I prefer to make child optional for ease of use.
        child = MyClass() if child is None else child
        self.child=child

mc=MyClass()
mc.set_child()

我个人更喜欢第一个解决方案,因为这意味着外部对象不需要了解有关该类的任何信息。当然,您可以将两者结合起来:

class MyClass:
    def __init__(self, create):
        if create:
            self.set_child(create=False)

    def set_child(self,child = None, create = True):
        child = MyClass(create) if child is None else child
        self.child=child

mc=MyClass()

这样 mc 默认情况下有一个子级,您可以选择随时设置子级。

还有一种“让我们创建一定数量”的方法:

class MyClass:
    def __init__(self, count = 10):
        count -= 1
        if count:
           # the first child gets the value 9.
           # the second gets 8.
           # when the count gets to 0, stop!
           self.child = MyClass(count)

旁白:如果你想获取一个对象的类,你可以使用值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:

class MyClass:
   def __init__(self, create = True):
      if create:
         self.child = MyClass(False)

mc = MyClass()

Or, you can have another, external method:

class MyClass:
    def set_child(self,child = None):
        # I prefer to make child optional for ease of use.
        child = MyClass() if child is None else child
        self.child=child

mc=MyClass()
mc.set_child()

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:

class MyClass:
    def __init__(self, create):
        if create:
            self.set_child(create=False)

    def set_child(self,child = None, create = True):
        child = MyClass(create) if child is None else child
        self.child=child

mc=MyClass()

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:

class MyClass:
    def __init__(self, count = 10):
        count -= 1
        if count:
           # the first child gets the value 9.
           # the second gets 8.
           # when the count gets to 0, stop!
           self.child = MyClass(count)

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.

待天淡蓝洁白时 2024-12-09 18:59:31

您正在进行无限递归调用 - MyClass 在初始化期间创建另一个 MyClass,因此它会无限递归。

您可能想做一些类似的事情:

class MyClass:
    def create_child(self):
        self.child=MyClass()

mc=MyClass()
mc.create_child()

如果您感觉特别顽皮,您可以尝试:

class MyClass(object):
    @property
    def child(self):
        if self._child is None: self._child = MyClass()
        return self._child

    def __init__(self):
        self._child=None

mc=MyClass()

You're making an infinitely recursing call — MyClass is creating another MyClass during initialization, and thus it recurses infinitely.

You may want to do something like:

class MyClass:
    def create_child(self):
        self.child=MyClass()

mc=MyClass()
mc.create_child()

If you're feeling particularly naughty, you could try:

class MyClass(object):
    @property
    def child(self):
        if self._child is None: self._child = MyClass()
        return self._child

    def __init__(self):
        self._child=None

mc=MyClass()
不爱素颜 2024-12-09 18:59:31

你所做的实际上是递归的,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.

莫相离 2024-12-09 18:59:31

我建议定义两个类:

class MyClass(object):
    def __init__(self):
        self.child = MyChildClass()
    ...many other methods...

class MyChildClass(MyClass):
    def __init__(self):
        pass

我认为如果两个类必须以两种不同的方式表现,那么它们一定是不同的(尽管一个类可以对另一个类进行子类化)

I suggest to define two classes:

class MyClass(object):
    def __init__(self):
        self.child = MyChildClass()
    ...many other methods...

class MyChildClass(MyClass):
    def __init__(self):
        pass

I think that if two classes must behave in two different ways, they must be different (although one can subclass the other)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文