在python3中是否可以为基本合成实例设置属性?

时间:2018-12-09 05:02:17

标签: python python-3.x oop composition

因此,我一直在阅读有关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 个答案:

答案 0 :(得分:0)

可以,但是您需要将该变量过滤掉。

class A:
    def __init__(self):
        self.x = 1

class B:
    def __init__(self, a):
        self.a = a
        self.x = 2
        self.y = 3  

    def __getattr__(self, attr):
        return getattr(self.a, attr)

    # setattr would have to be commented out here too
    def __setattr__(self, attr, val):
        if attr != "a":
            setattr(self.a, attr, val)
        else:
            super().__setattr__(attr, val)

a = A()
b = B(a)
print(a.x)
print(a.y)