簡體   English   中英

清單的Python屬性和設置器(如int和string)

[英]Python property and setter for list as for int and strings

我有一個帶有變量的類( intstringlist )。 我想使用@property獲取變量的值,使用setter設置此變量的值。 我可以為intstring變量實現此概念,但不能為list 請幫助我也將其實施在清單中。

class MyClass:

    def __init__(self):
        self._a = 1
        self._b = 'hello'
        self._c = [1, 2, 3]

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

    @a.setter
    def a(self, a):
        self._a = a

    @property
    def b(self):
        print(self._b)

    @b.setter
    def b(self, b):
        self._b = b


my = MyClass()

my.a
# Output: 1
my.a = 2
my.a
# Output: 2

my.b
# Output: hello
my.b = 'world'
my.b
# Output: world


# Need to implement:
my.c
# Output: [1, 2, 3]
my.c = [4, 5, 6]
my.c
# Output: [4, 5, 6]
my.c[0] = 0
my.c
# Output: [0, 5, 6]
my.c[0]
# Output: 0

我發現了類似的問題,但它們不適合我,因為以這種方式調用list的操作將不同於int和string:

所以我相信你的誤解,從沒有意識到, 一切都在Python是一種對象造成的。 liststringint之間沒有區別。 請注意,在實現intstring ,除了某些名稱之外沒有其他區別。

我已經用單個屬性重鑄了您的示例,然后將所有用例分配給它,以驗證該示例在所有情況下均有效。

碼:

class MyClass:
    def __init__(self):
        self.my_prop = None

    @property
    def my_prop(self):
        return self._my_prop

    @my_prop.setter
    def my_prop(self, my_prop):
        self._my_prop = my_prop

測試代碼:

my = MyClass()

my.my_prop = 1
assert 1 == my.my_prop
my.my_prop = 2
assert 2 == my.my_prop

my.my_prop = 'hello'
assert 'hello' == my.my_prop
my.my_prop = 'world'
assert 'world' == my.my_prop

my.my_prop = [1, 2, 3]
assert [1, 2, 3] == my.my_prop
my.my_prop = [4, 5, 6]
assert [4, 5, 6] == my.my_prop
my.my_prop[0] = 0
assert [0, 5, 6] == my.my_prop
assert 0 == my.my_prop[0]

暫無
暫無

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

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