【问题标题】:Is there a method/interface specific for an attribute in Python?Python中是否有特定于属性的方法/接口?
【发布时间】:2020-05-07 09:15:07
【问题描述】:
有没有办法在python中处理属性并返回所需值的方法?
下面是我想要实现的示例。
class Foo():
self.a = '123'
self.b = '234'
def hex_value(self,attribute): # method for attribute.
return hex(attribute)
if __name__=="__main__":
obj = Foo()
print(obj.a.hex) # should give hex value of 'a' by simply using dot operator.
【问题讨论】:
标签:
python
class
methods
attributes
【解决方案1】:
我觉得把这样的东西放在一起有点脏,但你可以使用某种代理类来做到这一点:
class Proxy():
def __init__(self, value, parent):
self.value = value
self.parent = parent
def __getattr__(self, attr):
return self.parent.__getattribute__(attr + '_value')(self.value)
class Foo():
def __init__(self):
self.a = '123'
self.b = '234'
self.c = 'foo_Bar'
def hex_value(self,attribute):
return hex(int(attribute))
def repeated_value(self,attribute):
return attribute + " " + attribute + " " + attribute
def __getattribute__(self, attr):
if not attr.endswith('_value') and not attr.startswith('__'):
return Proxy(super(Foo, self).__getattribute__(attr), self)
return super(Foo, self).__getattribute__(attr)
if __name__=="__main__":
obj = Foo()
print(obj.a.hex) # should give hex value of 'a' by simply using dot operator.
print(obj.c.repeated) # prints 'foo_Bar foo_Bar foo_Bar'
这个想法是您在Foo 中访问的所有内容都包含在代理中。而您在代理中访问的所有不可用的东西都会在代理的创建者上调用(添加了“_value”)。
但仅仅因为你可以并不意味着你应该。