在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('jiyik', 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('jiyik', 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('jiyik', 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('jiyik', 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()) # 👉️ jiyik
getattr
函数返回对象提供的属性的值。
该函数将对象、属性名称和属性在对象上不存在时的默认值作为参数。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。