classMLPEmployee:def__init__(self, emp_name):
self.emp_name = emp_name
defintroduce(self):print("Hello I am "+ self.emp_name)# create an object of MLPEmployee class
emp_1 = MLPEmployee("Mr Employee")print(emp_1.emp_name)#print employee name
emp_1.introduce()#introduce the employee
classMyClass:def__init__(self):
self.name ="Alice"defgreet(self):print("Hello, my name is", self.name)defsay_hello(self):print("Hello!")
obj = MyClass()print(dir(obj))
# Parent classclassParentClass:defpar_func(self):print("I am parent class function")# Child classclassChildClass(ParentClass):defchild_func(self):print("I am child class function")# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()
多层继承:父类 A 由子类 B 继承,子类 B 再由另一个子类 C 继承。基类和派生类的功能进一步继承到新的派生类 C 中。在这里,A 是 C 的祖父类。
# Parent classclassA:def__init__(self, a_name):
self.a_name = a_name
# Intermediate classclassB(A):def__init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)# Child classclassC(B):def__init__(self, c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)defdisplay_names(self):print("A name : ", self.a_name)print("B name : ", self.b_name)print("C name : ", self.c_name)# Driver code
obj1 = C('child','intermediate','parent')print(obj1.a_name)
obj1.display_names()
多重继承:当一个子类从多个父类派生成员时,就会实现这一点。 子类继承了父类的所有功能。
# Parent class1classParent1:defparent1_func(self):print("Hi I am first Parent")# Parent class2classParent2:defparent2_func(self):print("Hi I am second Parent")# Child classclassChild(Parent1, Parent2):defchild_func(self):
self.parent1_func()
self.parent2_func()# Driver's code
obj1 = Child()
obj1.child_func()
分层继承:当一个父类由多个子类派生时,称为分层继承。
# Base classclassA:defa_func(self):print("I am from the parent class.")# 1st Derived classclassB(A):defb_func(self):print("I am from the first child.")# 2nd Derived classclassC(A):defc_func(self):print("I am from the second child.")# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func()# child 1 method
obj2.a_func()
obj2.c_func()# child 2 method
43. 如何访问子类中的父类成员
以下是 Python 访问子类中的父类成员的方法:
通过使用父类名:可以使用父类的名称来访问属性,如下例所示:
classParent(object):# Constructordef__init__(self, name):
self.name = name
classChild(Parent):# Constructordef__init__(self, name, age):
Parent.name = name
self.age = age
defdisplay(self):print(Parent.name, self.age)# Driver Code
obj = Child("MLP",6)
obj.display()
classParent(object):# Constructordef__init__(self, name):
self.name = name
classChild(Parent):# Constructordef__init__(self, name, age):'''
In Python 3.x, we can also use super().__init__(name)
'''super(Child, self).__init__(name)
self.age = age
defdisplay(self):# Note that Parent.name cant be used # here since super() is used in the constructorprint(self.name, self.age)# Driver Code
obj = Child("MLP",6)
obj.display()