2017-03-31 57 views
0

我有一個類與變量(int,stringlist)。我想用@property來獲取變量的值,setter將值設置爲這個變量。我可以實現這個概念intstring變量,但不適用於list。請幫我把它也列入清單。Python屬性和設置列表爲int和字符串

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 

我也發現了類似的問題,但他們不適合我,因爲通過這種方式呼籲列表操作將從int和string不同:

+0

您可以修剪下來的[最小,完整,可驗證](http://stackoverflow.com/幫助/ mcve)的例子。這使我們更容易幫助你。 –

+0

@ stephen-rauch謝謝。我無意中從記事本中複製了兩次代碼。我刪除了我的代碼的副本。 –

+1

爲什麼你的屬性*打印*的價值,而不是返回它?爲什麼你甚至有屬性?當人們說你不需要Python中的getter和setter,因爲Python有屬性,這並不意味着你應該在任何地方使用屬性;這意味着你應該使用常規屬性,如果事實證明你需要附加一些邏輯來獲取或設置屬性,*然後*你帶一個'屬性'。 – user2357112

回答

0

所以我相信你的誤會源於沒有意識到的一切在python中是一個對象。 list,stringint之間沒有區別。請注意,在執行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]