>>> class A(object): pass
...
>>> A.__dict__
<dictproxy object at 0x173ef30>
>>> A.__dict__.__dict__
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
AttributeError: 'dictproxy' object has no attribute '__dict__'
>>> A.__dict__.copy()
{'__dict__': <attribute '__dict__' of 'A' objects> ... }
>>> A.__dict__['__dict__']
<attribute '__dict__' of 'A' objects> # What is this object?
Run Code Online (Sandbox Code Playgroud)
如果我这样做A.something = 10,这就进入了A.__dict__.什么是这个<attribute '__dict__' of 'A' objects>发现A.__dict__.__dict__,当它包含的东西吗?
我想通过字符串对象分配一个类属性 - 但是如何?
例:
class test(object):
pass
a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5
# BUT:
attr_name = 'next_value'
test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment
Run Code Online (Sandbox Code Playgroud) 假设我们要创建一系列类,这些类是总体概念的不同实现或特化。让我们假设某些派生属性有一个合理的默认实现。我们想把它放到一个基类中
class Math_Set_Base:
@property
def size(self):
return len(self.elements)
Run Code Online (Sandbox Code Playgroud)
因此,在这个相当愚蠢的示例中,子类将自动能够计算其元素
class Concrete_Math_Set(Math_Set_Base):
def __init__(self,*elements):
self.elements = elements
Concrete_Math_Set(1,2,3).size
# 3
Run Code Online (Sandbox Code Playgroud)
但是如果一个子类不想使用这个默认值怎么办?这不起作用:
import math
class Square_Integers_Below(Math_Set_Base):
def __init__(self,cap):
self.size = int(math.sqrt(cap))
Square_Integers_Below(7)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<stdin>", line 3, in __init__
# AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)
我意识到有一些方法可以用一个属性覆盖一个属性,但我想避免这种情况。因为基类的目的是让用户的生活尽可能简单,而不是通过强加(从子类的狭隘角度来看)复杂和多余的访问方法来增加膨胀。
可以做到吗?如果不是,下一个最佳解决方案是什么?
我想将装饰器应用于类中的每个方法.我没有类的源代码,所以我不能直接应用装饰器.我想调用一些接受类的函数并添加装饰器.
但问题是testclass.__dict__一个mappingproxy对象,它至少不直接支持任何赋值或修改.那么问题是如何避免这种刺激性限制并应用装饰器?
以下是尝试失败的代码:
class qwer:
def test(self):
print('test')
def decor(func):
def w(*args, **named_args):
print('decor')
func(*args, **named_args)
return w
qwer.__dict__['test'] = decor(qwer.__dict__['test'])
Run Code Online (Sandbox Code Playgroud)
错误:
TypeError: 'mappingproxy' object does not support item assignment
Run Code Online (Sandbox Code Playgroud) python ×4
class ×2
attributes ×1
decorator ×1
inheritance ×1
oop ×1
properties ×1
python-3.x ×1