在 python 中工作下一个代码:
class MyClass(object):
field = 1
>>> MyClass.field
1
>>> MyClass().field
1
当我想要自定义字段的返回值时,我使用下一个代码:
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
But:
>>> MyClass.fake
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class MyClass has no attribute 'fake'
好的,对于类我可以使用下一个代码:
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
But:
>>> MyClass().fake
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'fake'
为了解决这个问题,我使用下一个代码:
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
将会通知__getattr__
with MyClass
and fake
论据。
MyClass().fake
将会通知__getattr__
with MyClass
实例和fake
论据。
如果我实施就可以了__getattr__
逻辑仅在我的 mixin 上并且不使用self
争论。
我可以编写更漂亮的按类和实例解析的自定义值吗?为什么field
值解析为MyClass.field
and MyClass().field
with MyClass(object): field = 1
如果与以下内容比较,定义的效果会有所不同__getattr__
方法?因为当我想要得到field
它首先在实例中搜索,然后在课堂上搜索,但我不明白为什么__getattr__
另一种方式工作。
类似问题:__getattr__ 在类上而不是(或以及)实例上 https://stackoverflow.com/questions/11559120/getattr-on-a-class-and-not-or-as-well-as-an-instance and 访问实例属性和类属性之间的区别 https://stackoverflow.com/questions/1304868/difference-between-accessing-an-instance-attribute-and-a-class-attribute.