如何示例化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代码位于同一文件中)
5条答案
按热度按时间r1wp621o1#
由于解释器尚未定义名为ParentClass的类对象,因此不能在父类的定义中使用“ParentClass”。此外,在完全定义类ParentClass之前,将不会定义InternalClass。
注意:我知道你想做什么,但是如果你解释一下你的最终目标,我们也许可以建议你做一些其他的事情来实现这一点。
8dtrkrch2#
您可以执行以下操作:
例如,创建
Parent
类的示例,然后访问其Child
,如下所示:shyt4zoc3#
我不确定我是不是说对了但如果你想做那样的事
可以按如下所示创建AnotherChild对象
也可以按如下方式执行
或者直接通过您的init
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
mnowg1ta4#
寻找一个简单的例子
汽车等级:
在0x7fde1d8daeb0上创建一个汽车车轮对象
5us2dqdw5#
可以使用
__init__()
示例化外部类和内部类,如下所示:输出量: