有什么方法可以在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.
我觉得把这样的东西黑在一起有点脏,但你可以使用某种代理类来实现这个目标。
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')。
但是,你可以这样做并不意味着你应该这样做。