如何在python中示例化嵌套类

kx7yvsdv  于 2022-11-28  发布在  Python
关注(0)|答案(5)|浏览(167)

如何示例化UseInternalClass类型的变量?

MyInstance = ParentClass.UseInternalClass(something=ParentClass.InternalClass({1:2}))

如果我尝试使用前一个代码,会得到一个错误:

NameError: name 'ParentClass' is not defined

当我想示例化嵌套类的类型时

class ParentClass(object):
    class InternalClass(object):
        def __init__(self, parameter = {}):
            pass
        pass

    class UseInternalClass(object):
        _MyVar

        def __init__(self, something = ParentClass.InternalClass()): #meant to make something type = InternalClass
            _MyVar = something
        pass

(All代码位于同一文件中)

r1wp621o

r1wp621o1#

由于解释器尚未定义名为ParentClass的类对象,因此不能在父类的定义中使用“ParentClass”。此外,在完全定义类ParentClass之前,将不会定义InternalClass。
注意:我知道你想做什么,但是如果你解释一下你的最终目标,我们也许可以建议你做一些其他的事情来实现这一点。

8dtrkrch

8dtrkrch2#

您可以执行以下操作:

class Child:

    def __init__(self, y):
        self.y = y

class Parent:

    def __init__(self, x):
        self.x = x
        y = 2 * x
        self.child = Child(y)

例如,创建Parent类的示例,然后访问其Child,如下所示:

par = Parent(4)

par.child.y  # returns a value of 8
shyt4zoc

shyt4zoc3#

我不确定我是不是说对了但如果你想做那样的事

class Parent:
  class Child:
    def __init__(self,passed_data):
      self.data = passed_data
  class AnotherChild:
    def __init__(self,child=Parent.Child("no data passed"))
      self.child_obj = self.Child(data_to_pass)

可以按如下所示创建AnotherChild对象

another_child = Parent.AnotherChild() 
# here it will use the default value of "no data passed"

也可以按如下方式执行

child = Parent.Child("data") # create child object
another_child = Parent.AnotherChild(child) # pass it to new child

或者直接通过您的init

another_child = Parent.AnotherChild(Parent.Child("data"))

i guess this should work correctly if you are instantiating in the same file for example parent.py , it worked for me like that i am not sure if that what you want but i hope it helps

mnowg1ta

mnowg1ta4#

寻找一个简单的例子
汽车等级:

@classmethod
def create_wheel(cls):
    return cls.Wheel()

class Wheel:
    pass

在0x7fde1d8daeb0上创建一个汽车车轮对象

5us2dqdw

5us2dqdw5#

可以使用__init__()示例化外部类和内部类,如下所示:

class OuterClass:
    def __init__(self, arg): # Here
        self.variable = "Outer " + arg
        self.inner = OuterClass.InnerClass(arg)
        
    def outer_method(self, arg):
        print("Outer " + arg)
        
    class InnerClass:
        def __init__(self, arg): # Here
            self.variable = "Inner " + arg
            
        def inner_method(self, arg):
            print("Inner " + arg)

obj = OuterClass("variable") # Here
print(obj.variable)
print(obj.inner.variable)
obj.outer_method("method")
obj.inner.inner_method("method")

输出量:

Outer variable
Inner variable
Outer method
Inner method

相关问题