来自嵌套类python的属性

2024-10-01 15:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助打印嵌套类的属性。你知道吗

class SimpleClass(object):
    class NestedClass(object):
        def __init__(self):
            self.attribute = 1
    ...
    print(self.SimpleClass.attribute) # this doesnt work, how can i print attribute ?

我真的不知道怎么称呼它,我尝试了我所知道的一切,例如:

print(SimpleClass.NestedClass.attribute)
print(NestedClass.attribute)

。。。但什么都不管用

谢谢。你知道吗


Tags: self属性objectinitdefattributethiscan
2条回答

attribute仅在调用构造函数后为NestedClass的实例创建。没有attribute的初始值。如果您确实希望有一个默认值,那么您可以执行如下操作。。你知道吗

class SimpleClass(object):
    class NestedClass(object):
        attribute = 0
        def __init__(self):
            self.attribute = 1

attribute的基类起始值是0,任何实例都是1

>>> SimpleClass.NestedClass.attribute
0
>>> SimpleClass.NestedClass().attribute
1
>>> 

缺少大括号:

print(SimpleClass().NestedClass().attribute)

或者

print(SimpleClass.NestedClass().attribute)

相关问题 更多 >

    热门问题