获取 Python 中的类属性列表
获取一个类的属性列表:
-
使用
dir()
函数获取类属性名称的列表。 - 使用列表推导过滤掉以双下划线开头的属性和方法。
- 该列表将仅包含类的属性。
class Employee():
# 👇️ class variables
first = 'one'
second = 'two'
def __init__(self, id, name, salary):
# 👇️ instance variables
self.id = id
self.name = name
self.salary = salary
bob = Employee(1, 'jiyik', 100)
# ✅ 获取类属性列表
class_variables = [attribute for attribute in dir(Employee)
if not attribute.startswith('__')
and not callable(getattr(Employee, attribute))
]
print(class_variables) # 👉️ ['first', 'second']
# -----------------------------------------------------
# ✅ 获取实例属性列表
result = list(bob.__dict__.keys())
print(result) # 👉️ ['id', 'name', 'salary']
print(bob.__dict__) # 👉️ {'id': 1, 'name': 'jiyik', 'salary': 100}
dir
函数返回类属性名称的列表,并递归地返回其基类的属性。
class Employee():
# 👇️ class variables
first = 'one'
second = 'two'
def __init__(self, id, name, salary):
# 👇️ instance variables
self.id = id
self.name = name
self.salary = salary
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second']
print(dir(Employee))
class_variables = [attribute for attribute in dir(Employee)
if not attribute.startswith('__')
and not callable(getattr(Employee, attribute))
]
print(class_variables) # 👉️ ['first', 'second']
下一步是过滤掉所有以两个下划线开头的属性和所有方法。
我们使用列表推导来迭代名称列表。
列表推导用于对每个元素执行一些操作或选择满足条件的元素子集。
callable
函数将对象作为参数,如果对象看起来是可调用的,则返回 True,否则返回 False。
如果我们需要获取类变量和相应值的字典,则可以使用字典推导。
class Employee():
first = 'one'
second = 'two'
def __init__(self, id, name, salary):
self.id = id
self.name = name
self.salary = salary
result = {key: value for key, value in Employee.__dict__.items(
) if not key.startswith('__') and not callable(key)}
print(result) # 👉️ {'first': 'one', 'second': 'two'}
字典推导与列表推导非常相似。
它们对字典中的每个键值对执行一些操作,或者选择满足条件的键值对子集。
__dict__
属性返回一个包含对象属性和值的字典。
我们必须过滤掉以两个下划线和方法开头的键,就像前面的例子一样。
如果我们需要获取实例属性的列表,请使用 __dict__
属性。
class Employee():
# 👇️ class variables
first = 'one'
second = 'two'
def __init__(self, id, name, salary):
# 👇️ instance variables
self.id = id
self.name = name
self.salary = salary
bob = Employee(1, 'jiyik', 100)
result = list(bob.__dict__.keys())
print(result) # 👉️ ['id', 'name', 'salary']
print(bob.__dict__) # 👉️ {'id': 1, 'name': 'jiyik', 'salary': 100}
我们可以使用 dict.keys()
方法仅获取字典的键。
dict.keys
方法返回字典键的新视图。
最后一步是使用 list()
类将视图转换为列表。
相关文章
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 日期时间。