获取 Python 中的类属性列表

获取一个类的属性列表:

  1. 使用 dir() 函数获取类属性名称的列表。
  2. 使用列表推导过滤掉以双下划线开头的属性和方法。
  3. 该列表将仅包含类的属性。
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, 'zadmei', 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': 'zadmei', 'salary': 100}

获取 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


# ['__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, 'zadmei', 100)

result = list(bob.__dict__.keys())
print(result)  # ?️ ['id', 'name', 'salary']

print(bob.__dict__)  # ?️ {'id': 1, 'name': 'zadmei', 'salary': 100}

我们可以使用 dict.keys() 方法仅获取字典的键。

dict.keys 方法返回字典键的新视图。

最后一步是使用 list() 类将视图转换为列表。