当我在一个类中使用一个类时,我如何调用原始类的属性

2024-04-25 22:55:19 发布

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

在调用其他类中的类时,如何调用调用它的类中的嵌套路径中的属性

下面的例子是我自己解决这个问题的一个尝试。当然,这会导致一个错误,声称“example”没有定义,但我想我会展示它,让它清楚地表明我试图做什么

class CamelCase:
    def __init__(self):
        self.variable = 'foo'
        self.variable2  = CamelCase_2()


class CamelCase_2:
    def __init__(self):
        return example.variable        #this is the part i want to be able to do properly. 
                                       #using the attribute attribute 'variable' within CamelCase_2


example = CamelCase()
print(foo.variable2)

请注意,以上是我试图做的一个简化。假设我实际上试图在CameCase2中对example.variable使用函数upper()


Tags: thetoself路径属性fooinitexample
1条回答
网友
1楼 · 发布于 2024-04-25 22:55:19

CamelCase需要将自身传递给CamelCase_2

class CamelCase:
    def __init__(self):
        self.variable = 'foo'
        self.variable2  = CamelCase_2(self)


class CamelCase_2:
    def __init__(self, parent):
        self.camelcase = parent

然后CamelCase_2中的其他方法可以引用self.camelcase来访问创建它的对象

相关问题 更多 >

    热门问题