python - 属性和数据类属性的 getter 函数
问题描述
tl;博士我正在寻找一个速记lambda x: x.bar
如果我有课
class Foo:
def bar(self) -> int:
return 0
我可以用作从 a 获取属性Foo.bar
的一流函数,例如bar
Foo
foo = Foo()
getter = Foo.bar
getter(foo) # 0
当某些函数期望数据和 getter 作为单独的对象时,这很有用,并且不必编写lambda x: x.bar()
. 没关系。我想要的是与@property
s 和@dataclass
属性类似的东西。这是相同的方法不适用于属性
class Foo:
@property
def bar(self) -> int:
return 0
foo = Foo()
getter = Foo.bar
getter(foo)
Traceback (most recent call last):
File "....py", line 16, in <module>
getter(foo)
TypeError: 'property' object is not callable
有人知道这样做的方法吗?
解决方案
听起来您正在寻找operator.attrgetter
:
>>> from operator import attrgetter
>>> getter = attrgetter('bar')
>>> getter(foo)
0
同样的方法自然也适用于数据类属性:
>>> @dataclass
>>> class Baz:
... bar: int
>>> getter(Baz(1))
1