Python - Class Class Attributes


Python class has the following attribute:

__class__a link from an instance to the class from which it was created.
__name__ name of the class
__bases__ access to superclasses.
__dict__ a dictionary with one key/value pair for every attribute attached to a namespace object we can fetch its keys list, index by key, iterate over its keys, and so on


class Person: 
    def __init__(self, name, job=None, pay=0): = name # w  ww . ja va 2s  .  c  om
        self.job  = job  = pay 
    def lastName(self):                               # Behavior methods 
        return[-1]                  # self is implied subject 
    def giveRaise(self, percent): = int( * (1 + percent))      # Must change here only 

bob = Person('Bob Smith') 
                                           # Show bob's __repr__ (not __str__) 
print(bob)                                 # Ditto: print => __str__ or __repr__ 
print( bob.__class__ )                              # Show bob's class and its name 
print( bob.__class__.__name__ ) 
d = list(bob.__dict__.keys())                  # Attributes are really dict keys 
print( d )

for key in bob.__dict__: 
   print(key, '=>', bob.__dict__[key])    # Index manually 

for key in bob.__dict__: 
   print(key, '=>', getattr(bob, key))    # obj.attr, but attr is a var


Related Topics