感谢@ZachGates,我利用他的想法将其扩展为适用于类和对象:
class Parent(object):
def __init__(self):
pass
def parent_method(self):
print('parent')
@classmethod
def parent_class_method(self):
print('parent class method')
class Child(Parent):
def __init__(self):
pass
def child_method(self):
print('child')
@classmethod
def child_class_method(self):
print('child class method')
def is_inherited_instance_method(test_object, method_name):
"""
Gets the super object and looks up for it's method.
If the child has `method_name` atribute and parent doesn't,
then method is new.
"""
super_object = super(test_object.__class__, test_object)
if hasattr(test_object, method_name) and not hasattr(super_object, method_name):
# You can add extra checks, such as: callable() ...
print('it is a new method: %s' % method_name)
else:
print('method is not new: %s' % method_name)
def is_inherited_class_method(test_cls, method_name):
""" Does the same but only with Classes. """
super_cls = super(test_cls, test_cls)
if hasattr(test_cls, method_name) and not hasattr(super_cls, method_name):
# You can add extra checks, such as: callable() ...
print('it is a new class method: %s' % method_name)
else:
print('class method is not new: %s' % method_name)
parent = Parent()
child = Child()
is_inherited_instance_method(parent, 'parent_method')
is_inherited_instance_method(child, 'parent_method')
is_inherited_instance_method(child, 'child_method')
is_inherited_class_method(Parent, 'parent_class_method')
is_inherited_class_method(Child, 'parent_class_method')
is_inherited_class_method(Child, 'child_class_method')
输出是:
it is a new method: parent_method
method is not new: parent_method
it is a new method: child_method
it is a new class method: parent_class_method
class method is not new: parent_class_method
it is a new class method: child_class_method