我这样做:
def set_property(property,value):
def get_property(property):
or
object.property = value
value = object.property
python使用getter和setter的方法是什么?
我这样做:
def set_property(property,value):
def get_property(property):
or
object.property = value
value = object.property
python使用getter和setter的方法是什么?
当前回答
你可以使用神奇的方法__getattribute__和__setattr__。
class MyClass:
def __init__(self, attrvalue):
self.myattr = attrvalue
def __getattribute__(self, attr):
if attr == "myattr":
#Getter for myattr
def __setattr__(self, attr):
if attr == "myattr":
#Setter for myattr
注意__getattr__和__getattribute__是不同的。__getattr__只在未找到属性时调用。
其他回答
试试这个:Python属性
示例代码如下:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
print("getter of x called")
return self._x
@x.setter
def x(self, value):
print("setter of x called")
self._x = value
@x.deleter
def x(self):
print("deleter of x called")
del self._x
c = C()
c.x = 'foo' # setter called
foo = c.x # getter called
del c.x # deleter called
In [1]: class test(object):
def __init__(self):
self.pants = 'pants'
@property
def p(self):
return self.pants
@p.setter
def p(self, value):
self.pants = value * 2
....:
In [2]: t = test()
In [3]: t.p
Out[3]: 'pants'
In [4]: t.p = 10
In [5]: t.p
Out[5]: 20
这是一个老问题,但这个话题非常重要,而且一直是最新的。如果有人想超越简单的getter /setter,我已经写了一篇关于python中超级属性的文章,支持插槽,可观察性和简化的样板代码。
from objects import properties, self_properties
class Car:
with properties(locals(), 'meta') as meta:
@meta.prop(read_only=True)
def brand(self) -> str:
"""Brand"""
@meta.prop(read_only=True)
def max_speed(self) -> float:
"""Maximum car speed"""
@meta.prop(listener='_on_acceleration')
def speed(self) -> float:
"""Speed of the car"""
return 0 # Default stopped
@meta.prop(listener='_on_off_listener')
def on(self) -> bool:
"""Engine state"""
return False
def __init__(self, brand: str, max_speed: float = 200):
self_properties(self, locals())
def _on_off_listener(self, prop, old, on):
if on:
print(f"{self.brand} Turned on, Runnnnnn")
else:
self._speed = 0
print(f"{self.brand} Turned off.")
def _on_acceleration(self, prop, old, speed):
if self.on:
if speed > self.max_speed:
print(f"{self.brand} {speed}km/h Bang! Engine exploded!")
self.on = False
else:
print(f"{self.brand} New speed: {speed}km/h")
else:
print(f"{self.brand} Car is off, no speed change")
这个类可以这样使用:
mycar = Car('Ford')
# Car is turned off
for speed in range(0, 300, 50):
mycar.speed = speed
# Car is turned on
mycar.on = True
for speed in range(0, 350, 50):
mycar.speed = speed
这段代码将产生以下输出:
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Turned on, Runnnnnn
Ford New speed: 0km/h
Ford New speed: 50km/h
Ford New speed: 100km/h
Ford New speed: 150km/h
Ford New speed: 200km/h
Ford 250km/h Bang! Engine exploded!
Ford Turned off.
Ford Car is off, no speed change
更多关于如何和为什么的信息,请访问:https://mnesarco.github.io/blog/2020/07/23/python-metaprogramming-properties-on-steroids
你可以使用神奇的方法__getattribute__和__setattr__。
class MyClass:
def __init__(self, attrvalue):
self.myattr = attrvalue
def __getattribute__(self, attr):
if attr == "myattr":
#Getter for myattr
def __setattr__(self, attr):
if attr == "myattr":
#Setter for myattr
注意__getattr__和__getattribute__是不同的。__getattr__只在未找到属性时调用。
属性非常有用,因为你可以在赋值时使用它们,但也可以包括验证。你可以看到这段代码使用了装饰器@property和@<property_name>。Setter来创建方法:
# Python program displaying the use of @property
class AgeSet:
def __init__(self):
self._age = 0
# using property decorator a getter function
@property
def age(self):
print("getter method called")
return self._age
# a setter function
@age.setter
def age(self, a):
if(a < 18):
raise ValueError("Sorry your age is below eligibility criteria")
print("setter method called")
self._age = a
pkj = AgeSet()
pkj.age = int(input("set the age using setter: "))
print(pkj.age)
在我写的这篇文章中也有更多的细节:https://pythonhowtoprogram.com/how-to-create-getter-setter-class-properties-in-python-3/