Tôi sẽ có một mô-đun để giải quyết vấn đề này. Và đó là giải pháp Python2/3 tương thích. Và nó cho phép để kiểm tra với phương pháp được kế thừa từ lớp cha.
Thêm vào đó, mô-đun này cũng có thể kiểm tra:
- thuộc tính thường xuyên
- phương pháp phong cách sở hữu
- phương pháp thông thường
- staticmethod
- classmethod
Ví dụ:
class Base(object):
attribute = "attribute"
@property
def property_method(self):
return "property_method"
def regular_method(self):
return "regular_method"
@staticmethod
def static_method():
return "static_method"
@classmethod
def class_method(cls):
return "class_method"
class MyClass(Base):
pass
Đây là giải pháp cho staticmethod chỉ. Nhưng Tôi khuyên bạn nên sử dụng mô-đunposted here.
import inspect
def is_static_method(klass, attr, value=None):
"""Test if a value of a class is static method.
example::
class MyClass(object):
@staticmethod
def method():
...
:param klass: the class
:param attr: attribute name
:param value: attribute value
"""
if value is None:
value = getattr(klass, attr)
assert getattr(klass, attr) == value
for cls in inspect.getmro(klass):
if inspect.isroutine(value):
if attr in cls.__dict__:
binded_value = cls.__dict__[attr]
if isinstance(binded_value, staticmethod):
return True
return False
cảm ơn bạn đã chỉ cho tôi mô-đun "loại", tôi gần như quên nó. –