(OOP)语言的核心概念之一是继承。它是一种机制,允许您通过从另一个类派生一个类来创建共享一组属性和方法的类层次结构。继承是一个类从另一个类派生或继承属性的能力。
继承的好处是:
继承允许您将一个类(即基类)的属性继承到另一个类(即派生类)。Python中继承的好处如下:
Python中简单继承的语法如下:
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}
父类是其属性由子类继承的类。让我们创建一个名为Person的父类,它有一个Display方法来显示人员的信息。
# A Python program to demonstrate inheritance class Person(object): # Constructor def __init__(self, name, id): self.name = name self.id = id # To check if this person is an employee def Display(self): print(self.name, self.id) # Driver code emp = Person("Satyam", 102) # An Object of Person emp.Display()
输出:
Satyam 102
子类是从其父类驱动属性的类。这里Emp是另一个类,它将继承Person类(基类)的属性。
class Emp(Person): def Print(self): print("Emp class called") Emp_details = Emp("Mayank", 103) # calling parent class function Emp_details.Display() # Calling child class function Emp_details.Print()
Emp class called
让我们看一个简单的 Python 继承示例,其中子类继承其父类的属性。在此示例中,“Person”是父类,“Employee”是其子类。
# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket. # (Generally, object is made ancestor of all classes) # In Python 3.x "class Person" is # equivalent to "class Person(object)" class Person(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is an employee def isEmployee(self): return False # Inherited or Subclass (Note Person in bracket) class Employee(Person): # Here we return true def isEmployee(self): return True # Driver code emp = Person("Geek1") # An Object of Person print(emp.getName(), emp.isEmployee()) emp = Employee("Geek2") # An Object of Employee print(emp.getName(), emp.isEmployee())
Geek1 False Geek2 True
与Java 的 Object 类一样,在 Python(从版本 3.x 开始)中,对象是所有类的根。
子类需要识别哪个类是其父类。这可以通过在子类的定义中提及父类名称来完成。
示例:类子类名(超类名)
在此示例中,“a”是为类 Person 创建的实例。它调用所引用类的 init() 。您可以看到 Person 类的声明中写有“object”。在Python中,每个类都继承自一个名为“object”的内置基本类。当我们创建对象变量或类的实例时,会调用构造函数,即类的“init”函数。
init() 中定义的变量称为实例变量或对象。因此,“name”和“idnumber”是 Person 类的对象。同样,'salary' 和 'post' 是 Employee 类的对象。由于 Employee 类继承自 Person 类,因此“name”和“idnumber”也是 Employee 类的对象。
# Python code to demonstrate how parent constructors # are called. # parent class class Person(object): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) # child class class Employee(Person): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) # creation of an object variable or an instance a = Employee('Rahul', 886012, 200000, "Intern") # calling a function of the class Person using its instance a.display()
Rahul 886012
如果您忘记调用父类的 init() ,则子类将无法使用其实例变量。由于同样的原因,以下代码会产生错误。
class A: def __init__(self, n='Rahul'): self.name = n class B(A): def __init__(self, roll): self.roll = roll object = B(23) print(object.name)
输出 :
Traceback (most recent call last): File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in print (object.name) AttributeError: 'B' object has no attribute 'name'
super () 函数是一个内置函数,它返回代表父类的对象。它允许在子类中访问父类的方法和属性。
示例:具有简单 Python 继承的 super() 函数
在此示例中,我们创建了子类的对象“obj”。当我们调用子类“Student”的构造函数时,它将数据成员初始化为对象创建期间传递的值。然后使用 super() 函数,我们调用了父类的构造函数。
# parent class class Person(): def __init__(self, name, age): self.name = name self.age = age def display(self): print(self.name, self.age) # child class class Student(Person): def __init__(self, name, age): self.sName = name self.sAge = age # inheriting the properties of parent class super().__init__("Rahul", age) def displayInfo(self): print(self.sName, self.sAge) obj = Student("Mayank", 23) obj.display() obj.displayInfo()
Rahul 23 Mayank 23
继承提供的功能之一是继承父类的属性以及向子类添加我们自己的新属性。让我们通过一个例子来看看:
# parent class class Person(): def __init__(self, name, age): self.name = name self.age = age def display(self): print(self.name, self.age) # child class class Student(Person): def __init__(self, name, age, dob): self.sName = name self.sAge = age self.dob = dob # inheriting the properties of parent class super().__init__("Rahul", age) def displayInfo(self): print(self.sName, self.sAge, self.dob) obj = Student("Mayank", 23, "16-03-2000") obj.display() obj.displayInfo()
这里我们可以看到,我们在child类中添加了一个新的属性,即出生日期(dob)。
Rahul 23 Mayank 23 16-03-2000
Python 中有 5 种不同类型的继承。它们如下:
与 Java 不同,Python 表现出多重继承。
# Python example to show the working of multiple # inheritance class Base1(object): def __init__(self): self.str1 = "Geek1" print("Base1") class Base2(object): def __init__(self): self.str2 = "Geek2" print("Base2") class Derived(Base1, Base2): def __init__(self): # Calling constructors of Base1 # and Base2 classes Base1.__init__(self) Base2.__init__(self) print("Derived") def printStrs(self): print(self.str1, self.str2) ob = Derived() ob.printStrs()
Base1 Base2 Derived Geek1 Geek2
多级继承:当我们有子孙关系时。这意味着子类将从其父类继承,而父类又从其父类继承。
Python3
# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket. # (Generally, object is made ancestor of all classes) # In Python 3.x "class Person" is # equivalent to "class Person(object)" class Base(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # Inherited or Sub class (Note Person in bracket) class Child(Base): # Constructor def __init__(self, name, age): Base.__init__(self, name) self.age = age # To get name def getAge(self): return self.age # Inherited or Sub class (Note Person in bracket) class GrandChild(Child): # Constructor def __init__(self, name, age, address): Child.__init__(self, name, age) self.address = address # To get address def getAddress(self): return self.address # Driver code g = GrandChild("Geek1", 23, "Noida") print(g.getName(), g.getAge(), g.getAddress())
Geek1 23 Noida
我们并不总是希望子类继承父类的实例变量,即我们可以将父类的一些实例变量设为私有,这样子类就无法使用这些变量。
在Python继承中,我们可以通过在变量名称前添加双下划线将实例变量设为私有。例如:
# Python program to demonstrate private members # of the parent class class C(object): def __init__(self): self.c = 21 # d is private instance variable self.__d = 42 class D(C): def __init__(self): self.e = 84 C.__init__(self) object1 = D() # produces an error as d is private instance variable print(object1.c) print(object1.__d)
在这里我们可以看到,当我们尝试打印变量“c”时,它的值 21 被打印在控制台上。然而,当我们尝试打印“d”时,它生成了错误。这是因为变量“d”通过使用下划线设为私有。它不可用于子类“D”,因此会出现错误。
21 File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in print (object1.d) AttributeError: type object 'D' has no attribute 'd'
原文链接:codingdict.net