I have a class with variables ( int
, string
and list
). And I would like to use @property to get value of variables, setter to set values to this variables. I could implement this conception for int
and string
variables, but not for 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:
So I believe your misunderstanding stems from not realizing that everything in python is an object. There is no difference between the list
, the string
or the int
. Note that in your implementation for the int
and the string
there is no difference, except for some names.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.