python get parent class code example

Example 1: how to access parent class attribute from child class in python

# I've been searching for this for so long so i tought this might help you out.

class Person: #Parent class
  def __init__(self, fname, lname):
    self.fname = fname
    self.lname = lname
    
  def display(self):
    '''To check if parent method works'''
    print(self.fname)
    print(self.lname)
    
class Subscriber(Person): #Child class
  def __init__(self, fname, lname, ID):
    self.ID = ID
    
    #The part below this comment is the most important
    Person.__init__(self, fname, lname)
    #Make sure all arguments of the Parent class are in the Person.__init__()
    
  def displayID(self):
  '''To see if child method works'''
    print(self.ID)
	
John = Subscriber("John", "Doe", 1)
John.display()

#OUPUT:
#John
#Doe

John.displayID()
#OUTPUT
#1

Example 2: how to get the parent class using super python

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

Example 3: how to acess object of both parrents class python in single self

#definition of the class starts here  
class Person:  
    #defining constructor  
    def __init__(self, personName, personAge):  
        self.name = personName  
        self.age = personAge  
  
    #defining class methods  
    def showName(self):  
        print(self.name)  
  
    def showAge(self):  
        print(self.age)  
  
    #end of class definition  
  
# defining another class  
class Student: # Person is the  
    def __init__(self, studentId):  
        self.studentId = studentId  
  
    def getId(self):  
        return self.studentId  
  
  
class Resident(Person, Student): # extends both Person and Student class  
    def __init__(self, name, age, id):  
        Person.__init__(self, name, age)  
        Student.__init__(self, id)  
  
  
# Create an object of the subclass  
resident1 = Resident('John', 30, '102')  
resident1.showName()  
print(resident1.getId())