如何在python中实例化嵌套类

时间:2018-04-16 23:19:31

标签: python-3.x

如何实例化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

(所有代码都在同一个文件中)

3 个答案:

答案 0 :(得分:1)

你不能使用" ParentClass"在父类的定义内,因为解释器还没有定义名为ParentClass的类对象。此外,在完全定义ParentClass类之前,不会定义InternalClass。

注意:我要注意你要做的是什么,但是如果你解释了你的最终目标,我们可能会建议你做一些事情来实现这一点。

答案 1 :(得分:0)

您可以这样做:

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

答案 2 :(得分:0)

我不确定我是否正确,但是我是否要尝试做类似的事情

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"))

我想如果您在同一个文件中实例化该文件(例如parent.py),它应该可以正常工作 我不确定您想要的是什么,但希望对您有帮助

相关问题