[英]Python property and setter for list as for int and strings
我有一个带有变量的类( int
, string
和list
)。 我想使用@property获取变量的值,使用setter设置此变量的值。 我可以为int
和string
变量实现此概念,但不能为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是一种对象造成的。 list
, string
或int
之间没有区别。 请注意,在实现int
和string
,除了某些名称之外没有其他区别。
我已经用单个属性重铸了您的示例,然后将所有用例分配给它,以验证该示例在所有情况下均有效。
码:
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.