1

We can list all atributes(only atributes) of a class?

If we have, this class for example:

class c1():
    def __init__(self, x, y):
        self.fx = x
        self.fy = y
        self.fz = 0

    def fun1():
        return self.fx

With dir(c1) we get a full list with all objects of class, including atributes, however we can`t know the diference of methods and atributes.

I was think that will works:

type( dir(obj1)[-1] ) # [-1] Would be the last attribute, but the type return a string.

Sevila
  • 131
  • 4
  • 10

2 Answers2

2

You can use the __dict__ keyword to access attributes.

class c1():
    def __init__(self, x, y):
        self.fx = x
        self.fy = y
        self.fz = 0

    def fun1():
        return self.fx

obj1 = c1(1,2)
print(obj1.__dict__)

Output

{'fx': 1, 'fy': 2, 'fz': 0}

nathancy
  • 42,661
  • 14
  • 115
  • 137
2

Use __dict__.keys():

class c1():
    def __init__(self, x, y):
        self.fx = x
        self.fy = y
        self.fz = 0

    def fun1():
        return self.fx

obj1 = c1(1,2)
print(obj1.__dict__.keys())

Output: dict_keys(['fx', 'fy', 'fz'])

You might also want to look at pprint()

Alec
  • 8,529
  • 8
  • 37
  • 63