[英]Python property and setter for list as for int and strings
I have a class with variables ( int
, string
and list
). 我有一个带有变量的类(
int
, string
和list
)。 And I would like to use @property to get value of variables, setter to set values to this variables. 我想使用@property获取变量的值,使用setter设置此变量的值。 I could implement this conception for
int
and string
variables, but not for list
. 我可以为
int
和string
变量实现此概念,但不能为list
。 Please, help me to implement it for list too. 请帮助我也将其实施在清单中。
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
I have found similar questions, but they don't suit for me, because in this way calling operations for list would differ from int and string: 我发现了类似的问题,但它们不适合我,因为以这种方式调用list的操作将不同于int和string:
So I believe your misunderstanding stems from not realizing that everything in python is an object. 所以我相信你的误解,从没有意识到, 一切都在Python是一种对象造成的。 There is no difference between the
list
, the string
or the int
. list
, string
或int
之间没有区别。 Note that in your implementation for the int
and the string
there is no difference, except for some names. 请注意,在实现
int
和string
,除了某些名称之外没有其他区别。
I have recast your example with a single property, and then assigned all of your use cases to it to verify that it works in all cases. 我已经用单个属性重铸了您的示例,然后将所有用例分配给它,以验证该示例在所有情况下均有效。
Code: 码:
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
Test Code: 测试代码:
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.