【问题标题】:Outputting all class variables in Python 3.7 [duplicate]在 Python 3.7 中输出所有类变量 [重复]
【发布时间】:2020-08-02 20:45:41
【问题描述】:

我正在关注 Python 类的教程。我想输出所有类变量,但 raise_amount 由于某种原因没有出现。这是我的类定义以及一个实例 emp_1:

class Employee:
    
    raise_amount = 1.04
    
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
    
emp_1 = Employee('Corey', 'Schafer', 50000)

这两个语句做同样的事情,但都不显示 raise_amount:

print(vars(emp_1))
print(emp_1.__dict__)
{'first': 'Corey', 'last': 'Schafer', 'pay': 50000}
{'first': 'Corey', 'last': 'Schafer', 'pay': 50000}

有没有更新的方法来输出类变量(Python 3.7)?以上语句在视频中有效,但它是从 2016 年开始的。我仍然可以引用 raise_amount(见下文),只是在输出所有类变量时看不到它。

print(emp_1.raise_amount)
1.04

【问题讨论】:

    标签: python-3.x class variables


    【解决方案1】:

    使用dir函数:

    print(dir(emp_1))
    

    很遗憾,没有办法区分“用户定义”属性和内置属性,但如果您想排除魔术方法,可以使用列表推导:

    def get_public_attrs(instance):     
        return [attr for attr in dir(instance) if not attr.startswith('_')]
    
    print(get_public_attrs(emp_1))
    ['first', 'last', 'pay', 'raise_amount']
    

    【讨论】:

    • 请不要同时回答问题将其标记为重复
    • @DeepSpace 为什么?
    • TLDR 如果它是重复的,则将其标记为这样。如果不是,请回答。如果是重复的,您可以提供更好的答案,标记为重复并回答原始问题meta.stackexchange.com/questions/10841/…
    • @DeepSpace 该链接仅说明 什么 我应该做,而不是 为什么 我应该这样做。
    • @sobrio35 查看我的更新
    猜你喜欢
    • 2021-07-04
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多