1

I'm following a tutorial on Python classes. I want to output all class variables, but raise_amount doesn't show up for some reason. Here's my class definition along with one instance, 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)

These 2 statements do the same thing, but neither displays raise_amount:

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

Is there a newer way to output the class variables (Python 3.7)? The above statements worked in the video, but it's from 2016. I can still reference raise_amount (see below), just can't see it when outputting all the class variables.

print(emp_1.raise_amount)
1.04
sobrio35
  • 143
  • 1
  • 10

1 Answers1

0

Use the dir function:

print(dir(emp_1))

Unfortunately, there isn't a way to distinguish between "user-defined" attributes and builtin ones, but if you want to exclude magic methods, you can use list comprehension:

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']
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80