簡體   English   中英

Python屬性setter如何進行多級設置?

[英]Python property setter how to do multistage setting?

我創建了兩個A和B類(使用@property來獲取和設置它們的屬性)。 B類有一個類型為A類的成員。如何設置bax的屬性?

A類:

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 ?

我使用@property錯了嗎?

你的代碼工作正常,但如果你正在尋找另一種方法,你可以繼承A類, bax變成bx

您可以通過在B的構造函數中添加以下行來實現此目的

super(A, self).__init__()

因此bax == bx

將print()添加到您的類中會顯示行為,調用bax = 1將使A類中的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

如果你想讓a.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM