Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python 3.7中输出所有类变量_Python 3.x_Class_Variables - Fatal编程技术网

Python 3.x 在Python 3.7中输出所有类变量

Python 3.x 在Python 3.7中输出所有类变量,python-3.x,class,variables,Python 3.x,Class,Variables,我正在学习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

我正在学习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)
这两条语句的作用相同,但都不显示“增加金额”:

print(vars(emp_1))
print(emp_1.__dict__)
是否有更新的方法输出类变量(Python3.7)?上述声明在视频中起作用,但它是从2016年开始的。我仍然可以引用raise_amount(见下文),只是在输出所有类变量时看不到它

print(emp_1.raise_amount)
使用功能:

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']

请不要同时回答一个问题并将其标记为duplicate@DeepSpace为什么?TLDR如果它是重复的,请将其标记为重复。如果不是,请回答。如果是重复的,您可以提供更好的答案,请标记为重复,然后回答原始问题@DeepSpace that link只是说明我应该做什么,而不是为什么要做。@sobrio35查看我的更新
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']