所以,我一直在阅读Python中的组合,我想知道是否有一种方法来集成设置“基础对象”属性而不特别指向“基类”(如下面代码的注释部分所做的那样) .
所以,我正在寻找下面剪切的代码来打印:
1
2
3
4
Success
但是,通过这个片段,我生成了一个RecursionError .
是否有一种方法(self.a.x = n除外)更新A类的属性,以便与其他组合类共享(本例中为C类)?
class A:
def __init__(self):
self.x = 1
class B:
def __init__(self, a):
self.a = a
self.y = 2
print(self.x)
print(self.y)
self.x = 3
# would work if "self.a.x = 3"
# and "__setattr__" commented out
def __getattr__(self, attr):
return getattr(self.a, attr)
# setattr would have to be commented out here too
def __setattr__(self, attr, val):
setattr(self.a, attr, val)
class C:
def __init__(self, a):
self.a = a
print(self.x)
self.x = 4
print(self.x)
try:
print(self.y)
except AttributeError:
print('Sucess')
def __getattr__(self, attr):
return getattr(self.a, attr)
def __setattr__(self, attr, val):
setattr(self.a, attr, val)
a = A()
b = B(a)
c = C(a)
1 回答
这是可能的,但您需要过滤掉该变量 .