获取python中的类和实例的属性 [英] Get attributes for class and instance in python

查看:187
本文介绍了获取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将使用MyClassfake自变量调用__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.fieldMyClass().fieldfield值解析方法工作不同?因为当我想要先获取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一个类而不是一个实例(或一个实例)推荐答案

否,如果您既要在类上又要在实例上同时支持任意属性查找,那么您唯一的选择是实现__getattr__ hook方法在元类和类上,每个都支持对类和实例的查找.

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 __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__.请参见用于新型类的特殊方法查找;我解释了为什么在上一个答案中.

This is because special hook methods are always looked up on the type, so 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__然后是一个需要两个参数(selfname)的未绑定方法,会失败的.

The short reason is that in your case, MyClass.fake would translate into MyClass.__getattr__('fake') and __getattr__ is then an unbound method expecting two arguments (self and name), which would fail.

这篇关于获取python中的类和实例的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆