获取python中的类和实例的属性 [英] Get attributes for class and instance in python
问题描述
在python中工作下一个代码:
In python work next code:
class MyClass(object):
field = 1
>>> MyClass.field
1
>>> MyClass().field
1
当我想为自定义字段返回值时,我使用下一个代码:
When I want return value for custom fields I use next code:
class MyClass(object):
def __getattr__(self, name):
if name.startswith('fake'):
return name
raise AttributeError("%r object has no attribute %r" %
(type(self).__name__, name))
>>> MyClass().fake
fake
但是:
>>> MyClass.fake
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class MyClass has no attribute 'fake'
好,对于课程,我可以使用下一个代码:
Ok, for classes I can use next code:
class MyClassMeta(type):
def __getattr__(cls, name):
if name.startswith('fake'):
return name
raise AttributeError("%r object has no attribute %r" %
(type(self).__name__, name))
class MyClass(object):
__metaclass__ = MyClassMeta
>>> MyClass.fake
fake
但是:
>>> MyClass().fake
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'fake'
要解决此问题,我使用下一个代码:
To resolve this problem I use next code:
class FakeAttrMixin():
def __getattr__(self, name):
if name.startswith('fake'):
return name
raise AttributeError("%r object has no attribute %r" %
(type(self).__name__, name))
class MyClassMeta(type, FakeAttrMixin):
pass
class MyClass(object, FakeAttrMixin):
__metaclass__ = MyClassMeta
>>> MyClass.fake
fake
>>> MyClass().fake
fake
MyClass.fake
将使用MyClass
和fake
自变量调用__getattr__
.
MyClass.fake
will call __getattr__
with MyClass
and fake
arguments.
MyClass().fake
将使用MyClass
实例和fake
自变量调用__getattr__
.
MyClass().fake
will call __getattr__
with MyClass
instance and fake
arguments.
如果我仅在我的mixin上实现__getattr__
逻辑并且不使用self
参数,那是可以的.
And it's ok if I implement __getattr__
logic only on my mixin and don't use self
argument.
我可以编写更漂亮的类和实例自定义值解析方法吗,为什么与__getattr__
方法相比,使用MyClass(object): field = 1
定义的MyClass.field
和MyClass().field
的field
值解析方法工作不同?因为当我想要先获取field
时,它首先在实例中搜索,然后在类中搜索,但是我不明白为什么__getattr__
可以以另一种方式工作.
Can I write custom value resolving by class and instance more beautiful and why field
value resolving for MyClass.field
and MyClass().field
with MyClass(object): field = 1
definition works different if compare with __getattr__
method? Because when I want get field
it at first searching in instance, then in class, but I can't understand why __getattr__
works another way.
相似的问题: __getattr__ on一个类而不是一个实例(或一个实例)和推荐答案
否,如果您既要在类上又要在实例上同时支持任意属性查找,那么您唯一的选择是实现 No, if you have to support both arbitrary attribute lookup on the class as well as the instance, then your only option is to implement a 这是因为总是在类型上查找特殊的钩子方法,因此 This is because special hook methods are always looked up on the type, so 简短的原因是,在您的情况下, The short reason is that in your case, 这篇关于获取python中的类和实例的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!__getattr__
hook方法在元类和类上,每个都支持对类和实例的查找.__getattr__
hook method on both the metaclass and the class, one each to support lookups on the class and the instance.type(obj).__getattr__
.因此,对于MyClass.fake
,使用元类__getattr__
.请参见用于新型类的特殊方法查找;我解释了为什么在上一个答案中.type(obj).__getattr__
. Hence, for MyClass.fake
the metaclass __getattr__
is used. See Special method lookup for new-style classes; I explained why this is in a previous answer.MyClass.fake
会转换为MyClass.__getattr__('fake')
,而__getattr__
然后是一个需要两个参数(self
和name
)的未绑定方法,会失败的.MyClass.fake
would translate into MyClass.__getattr__('fake')
and __getattr__
is then an unbound method expecting two arguments (self
and name
), which would fail.