2017-03-31 126 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]