7 python
这是我的猜测,这不起作用:
class BaseClass(object):
def foo(self):
return 'foo'
def bar(self):
return 'bar'
def methods_implemented(self):
"""This doesn't work..."""
overriden = []
for method in ('foo', 'bar'):
this_method = getattr(self, method)
base_method = getattr(BaseClass, method)
if this_method is not base_method:
overriden.append(method)
return overriden
class SubClass(BaseClass):
def foo(self):
return 'override foo'
o = SubClass()
o.methods_implemented()
Run Code Online (Sandbox Code Playgroud)
理想情况下,methods_implemented()将返回['foo'].
怎么样?
(为什么我要这样做?我的基类是一个HTTP资源类,它有方法GET,POST等.默认情况下它们返回405方法未实现.它还有一个方法OPTIONS,它应返回200响应,标题为Allow设置为任何子类实现的方法.)
Ned*_*ily 10
也许这个?
>>> class BaseClass(object):
... def foo(self):
... return 'foo'
... def bar(self):
... return 'bar'
... def methods_implemented(self):
... """This does work."""
... overriden = []
... for method in ('foo', 'bar'):
... this_method = getattr(self, method)
... base_method = getattr(BaseClass, method)
... if this_method.__func__ is not base_method.__func__:
... overriden.append(method)
... return overriden
...
>>> class SubClass(BaseClass):
... def foo(self):
... return 'override foo'
...
>>> o = SubClass()
>>> o.methods_implemented()
['foo']
Run Code Online (Sandbox Code Playgroud)
这将检查绑定方法后面的函数对象是否相同.
请注意,在Python 2.6之前,该__func__属性已命名im_func.
| 归档时间: |
|
| 查看次数: |
2483 次 |
| 最近记录: |