[英]Python Accessing to the parent class (Not inheritance)
Is possible access to the parent methods/properties in a class that are inside of the other class? 是否可以访问另一个类内部的类中的父方法/属性?
class ClassA:
a = 'a'
class ClassB():
def method(self):
return self.a
instance = ClassA()
instance2 = instance.ClassB()
instance2.method()
No, nesting a class doesn't automatically produce a relationship between instances. 不,嵌套类不会自动在实例之间产生关系。 All you did was create an attribute on
ClassA
that happens to be a class object. 您所做的就是在
ClassA
上创建一个碰巧是类对象的属性。 Calling that attribute on instances just finds the class attribute and a new instance of ClassB
is created without any knowledge of or reference to the ClassA
instance. 在实例上调用该属性只会找到类属性,并且会在不了解或未引用
ClassA
实例的情况下创建ClassB
的新实例。
You'll need to make such relationships explicit by passing in a reference: 您需要通过传递参考来使这种关系明确:
class ClassB():
def __init__(self, a):
self.a = a
def method(self):
return self.a
class ClassA:
a = 'a'
def class_b_factory(self):
return ClassB(self)
instance = ClassA()
instance2 = instance.class_b_factory()
instance2.method()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.