Py学习  »  Python

python属性设置器如何进行多级设置?

rivergold • 6 年前 • 1617 次点击  

我已经创建了两个类A和B(使用 @property 获取并设置它们的属性)。B类有一个类型为A类的成员。如何设置 b.a.x 是吗?

甲级:

class A(object):
    def __init__(self, x=0, y=0):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, value):
        self._y = value

B类:

class B(object):
    def __init__(self):
        self._a = A()

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        if isinstance(value, A):
            self._a = deepcopy(value)
        elif isinstance(value, tuple):
            self._a = A(value[0], value[1])
        elif isinstance(value, int):
            # ?           
            pass
b = B()
b.a.x = 1 # How to implementate this ?

我是不是用错了 @房产 是吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48093
文章 [ 2 ]  |  最新文章 6 年前
SuperCode
Reply   •   1 楼
SuperCode    7 年前

您的代码运行良好,但是如果您正在寻找另一种方法,则可以继承 A 类和 b.a.x 变成 b.x 是的。

您可以通过在 B 的构造函数

super(A, self).__init__()

因此 b.a.x == b.x

Mahmoud Elshahat
Reply   •   2 楼
Mahmoud Elshahat    7 年前

向类中添加print()将显示行为,调用 b.a.x = 1 将使x.setter在一个负责的类中,而不是b类中的a.setter

例子:

class A(object)
    .
    .
    @x.setter
    def x(self, value):
        print('x.setter acting')
        self._x = value


class B(object):
    .
    .
    @a.setter
    def a(self, value):
        print('a.setter acting')  # adding print 
        if isinstance(value, A):
            self._a = deepcopy(value)
        elif isinstance(value, tuple):
            self._a = A(value[0], value[1])
        elif isinstance(value, int):
            # ?           
            pass

b = B()
b.a.x = 1 # x.setter will be in charge not a.setter

输出:

x.setter acting

如果您希望由.setter负责,您可以:

class B(object):
        .
        .
        @a.setter
        def a(self, value):
            print('a.setter acting')  # adding print 
            if isinstance(value, A):
                self._a = deepcopy(value)
            elif isinstance(value, tuple):
                self._a = A(value[0], value[1])
            elif isinstance(value, int):
                # ?           
                self._a.x = value

b = B()
b.a = 1 # a.setter will be in charge

输出:

a.setter acting