Python如何按定义顺序将类变量存入数组且无需通过self提前初始化
实现方案
Python 3.7及以上版本(主流版本,原生支持)
Python 3.7开始默认保留类属性的定义顺序,直接读取类的属性字典过滤内置属性即可,不需要初始化self相关属性:
class Person: name = "" surname = "" age = "" def __init__(self): # 过滤双下划线开头的系统内置属性,剩余属性按定义顺序返回 arr = [attr for attr in Person.__dict__ if not attr.startswith('__')] print(arr) # 输出结果:['name', 'surname', 'age'] # 测试代码 Person()
进阶过滤(可选)
如果你的类后续会添加类方法、其他类型的类属性,需要进一步过滤只保留字符串类型的类变量,可以修改为:
arr = [ attr for attr, val in Person.__dict__.items() if not attr.startswith('__') and isinstance(val, str) ]
低版本Python兼容(Python 3.6及以下)
低版本Python类属性字典默认无序,你可以借助dataclasses模块实现顺序保留:
from dataclasses import dataclass @dataclass class Person: name: str = "" surname: str = "" age: str = "" def __init__(self): arr = list(self.__annotations__.keys()) print(arr) # 输出结果:['name', 'surname', 'age']
内容的提问来源于stack exchange,提问作者ThomasCodesThings
相关产品推荐
相关产品推荐

