在Python中获取给定类的所有方法
使用 inspect.getmembers() 方法获取一个类的所有方法,例如 inspect.getmembers(Employee, predicate=inspect.isfunction)。 getmembers() 方法将返回一个包含该类的所有方法的列表。
import inspect
class Employee():
def __init__(self, name, salary):
self.salary = salary
self.name = name
def get_name(self):
return self.name
def get_salary(self):
return self.salary
# ?️ 用类本身调用 inspect.getmembers
list_of_methods = inspect.getmembers(Employee, predicate=inspect.isfunction)
# ?️ [('__init__', <function Employee.__init__ at 0x7f91845bdab0>), ('get_name', <function Employee.get_name at 0x7f9184696e60>), ('get_salary', <function Employee.get_salary at 0x7f9184696ef0>)]
print(list_of_methods)
# ------------------------------------------------------------------
bob = Employee('zadmei', 100)
# ?️ 用类的实例调用 inspect.getmembers
list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod)
# [('__init__', <bound method Employee.__init__ of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_name', <bound method Employee.get_name of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_salary', <bound method Employee.get_salary of <__main__.Employee object at 0x7fca7bac09d0>>)]
print(list_of_methods)
我们使用了 inspect.getmembers() 方法来获取一个包含类的所有方法的列表。
inspect.getmembers 方法接受一个对象并在一个元组列表中返回该对象的所有成员。
每个元组中的第一个元素是成员的名称,第二个元素是值。
我们将谓词参数设置为 inspect.function 来获取仅包含类方法的列表。
inspect.getmembers() 方法也可以传递一个类的实例,但是我们必须将谓词更改为 inspect.ismethod。
import inspect
class Employee():
def __init__(self, name, salary):
self.salary = salary
self.name = name
def get_name(self):
return self.name
def get_salary(self):
return self.salary
bob = Employee('zadmei', 100)
list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod)
# [('__init__', <bound method Employee.__init__ of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_name', <bound method Employee.get_name of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_salary', <bound method Employee.get_salary of <__main__.Employee object at 0x7fca7bac09d0>>)]
print(list_of_methods)
如果对象是 Python 函数,inspect.isfunction 谓词返回 True。
如果对象是用 Python 编写的绑定方法,则 inspect.ismethod 谓词返回 True。
确保在将类传递给 inspect.getmembers() 方法时使用 inspect.isfunction,在将实例传递给 getmembers() 时使用inspect.ismethod。
或者,我们可以使用 dir() 函数。
使用 dir() 获取给定类的所有方法
获取给定类的所有方法:
- 使用 dir() 函数获取类属性名称的列表。
- 使用列表推导过滤掉以双下划线开头的属性和所有非方法。
- 该列表将仅包含类的方法。
class Employee():
def __init__(self, name, salary):
self.salary = salary
self.name = name
def get_name(self):
return self.name
def get_salary(self):
return self.salary
class_methods = [method for method in dir(Employee)
if not method.startswith('__')
and callable(getattr(Employee, method))
]
print(class_methods) # ?️ ['get_name', 'get_salary']
过滤掉以下划线开头的属性是可选的。
如果我们需要保留以两个下划线开头的方法名称,请确保删除该条件。
class_methods = [method for method in dir(Employee)
if callable(getattr(Employee, method))
]
# ['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'get_name', 'get_salary']
print(class_methods)
class_methods 列表包含该类的所有方法名称。
我们也可以使用这种方法来获取实例的所有方法。
class Employee():
def __init__(self, name, salary):
self.salary = salary
self.name = name
def get_name(self):
return self.name
def get_salary(self):
return self.salary
bob = Employee('zadmei', 100)
class_methods = [method for method in dir(bob)
if not method.startswith('__')
and callable(getattr(bob, method))
]
print(class_methods) # ?️ ['get_name', 'get_salary']
如果需要调用某些方法,可以使用 getattr 函数。
bob = Employee('zadmei', 100)
class_methods = [method for method in dir(bob)
if not method.startswith('__')
and callable(getattr(bob, method))
]
print(class_methods) # ?️ ['get_name', 'get_salary']
method_1 = getattr(bob, class_methods[0])
print(method_1()) # ?️ zadmei
getattr 函数返回对象提供的属性的值。
该函数将对象、属性名称和属性在对象上不存在时的默认值作为参数。