class MyModel(object) : pass
modelClass = MyModel()
class ModelResource(object):
def mymethod(self):
print('got here')
Meta = type('Meta', (object, ), {'allowed_methods': ['get']})
def add_mymethod(cls):
def mymethod(self):
super(cls, self).mymethod()
cls.mymethod = mymethod
return cls
name = modelClass.__class__.__name__ + "Resource"
MyModelResource = add_mymethod(type(name, (ModelResource, ),
{'Meta':Meta, }))
print(MyModelResource.Meta)
# <class '__main__.Meta'>
m = MyModelResource()
m.mymethod()
# got here
就其而言,内部类Meta只是另一个属性MyModelResource。
就所关心的而言,方法也只是属性MyModelResource。实际上,您在 中定义了一个函数,MyModelResource.__dict__而 Python 属性查找机制会导致inst.mymethod返回一个绑定方法。
调用MyModelResource中提到没有问题super
super(MyModelResource, self).mymethod()
beforeMyModelResource已定义,因为名称查找是在运行时执行的,而不是在mymethod定义时执行的。
你是绝对正确的
super(self.__class_, self).mymethod()
是错的。这将破坏一切美好的事物super。如果MyModelResource要被子类化,并且要调用子类的一个实例mymethod,那么 Python 将陷入无限循环。