python get parent class code example
Example 1: how to access parent class attribute from child class in python
class Person:
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):
def __init__(self, fname, lname, ID):
self.ID = ID
Person.__init__(self, fname, lname)
def displayID(self):
'''To see if child method works'''
print(self.ID)
John = Subscriber("John", "Doe", 1)
John.display()
John.displayID()
Example 2: how to get the parent class using super python
class Foo(Bar):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Example 3: how to acess object of both parrents class python in single self
class Person:
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
class Student:
def __init__(self, studentId):
self.studentId = studentId
def getId(self):
return self.studentId
class Resident(Person, Student):
def __init__(self, name, age, id):
Person.__init__(self, name, age)
Student.__init__(self, id)
resident1 = Resident('John', 30, '102')
resident1.showName()
print(resident1.getId())