包阅导读总结
1. 关键词:Python、Inheritance、Base Class、Derived Class、Object-Oriented Programming
2. 总结:本文介绍了 Python 中面向对象编程的继承特性,包括基类、派生类的概念,不同类型的继承,继承的好处,通过示例展示了如何创建和使用继承,还介绍了`super()`函数的使用。
3. 主要内容:
– 介绍面向对象编程中的继承概念,其能使新类继承现有类的属性和方法,使代码更简洁易读。
– 解释类的概念,如基类和派生类。
– 阐述五种继承类型:单继承、多继承、多级继承、分层继承、混合继承。
– 列举继承的好处。
– 展示基本的类继承语法,通过示例创建基类`Person`,并从其派生出`Staff`类。
– 新增函数到基类,并创建派生类`Employee`进行演示。
– 介绍`super()`函数,通过`Student`类的示例展示其使用。
思维导图:
文章地址:https://thenewstack.io/how-to-use-inheritance-in-python/
文章来源:thenewstack.io
作者:Jack Wallen
发布时间:2024/8/9 17:51
语言:英文
总字数:1273字
预计阅读时间:6分钟
评分:88分
标签:Python,继承,面向对象编程,代码重用,编程教程
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
In object-oriented programming, there’s a feature called inheritance that allows a new class to inherit the attributes and methods of an existing class. By using inheritance, you don’t have to always reinvent the wheel, which also means your code will be more concise and easier to read and debug.
First, what is a class?
Think of a class as a blueprint for creating objects, and also for defining the properties (attributes) and behaviors (methods) that will be associated with the objects created from the class. A class is like a template you can use and reuse within your code.
Inheritance requires two types of classes:
- Base class (aka parent class): This is the class whose attributes and methods will be inherited.
- Derived class (aka child class): This is the class that inherits the attributes and methods.
There are five types of inheritance:
- Single inheritance: A derived class inherits from a single base class.
- Multiple inheritance: A derived class inherits from multiple base classes.
- Multilevel inheritance: A class is derived from a class, which is derived from another class.
- Hierarchical inheritance: Multiple classes are derived from a single base class.
- Hybrid inheritance: A combination of two or more types of inheritance.
The benefits of using inheritance include:
The basic syntax of class inheritance looks like this:
class baseClass: # Base class attributes and methods
class derivedClass(baseClass) # Derived class attributes and methods |
Let’s first create a base class. This will make use of several concepts I’ve outlined throughout this Python series.
We’ll create a base class that defines a person’s name and looks like this:
class Person: def __init__(fullName, fname, lname): fullName.firstname = fname fullName.lastname = lname
def printname(fullName): print(fullName.firstname, fullName.lastname) |
Now that we’ve created our class, we then use it to create an object and print the object like so:
x = Person(“Jack”, “Wallen”) x.printname() |
Put all of that together and it looks like this:
class Person: def __init__(fullName, fname, lname): fullName.firstname = fname fullName.lastname = lname
def printname(fullName): print(fullName.firstname, fullName.lastname)
x = Person(“Jack”, “Wallen”) x.printname() |
Run the above command and it will print “Jack Wallen”.
That’s the base class. We’ve create a derived class that inherits the attributes and methods from the base class (Person). This is the easy part. We’ll create a new class, named Staff, which inherits from Person. The class looks like this:
class Staff(Person) pass |
By using pass, we inform Python that we’re not adding any new attributes or methods to the new class.
We can then create a new object from the derived class like so:
x = Staff(“Olivia”, “Nightingale”) |
Print the new object with:
The entire code now looks like this:
class Person: def __init__(fullName, fname, lname): fullName.firstname = fname fullName.lastname = lname
def printname(fullName): print(fullName.firstname, fullName.lastname)
x = Person(“Jack”, “Wallen”) x.printname()
class Staff(Person): pass
x = Staff(“Olivia”, “Nightingale”) x.printname() |
Run the above code and it will print:
Jack Wallen
Olivia Nightingale
Remember that we previously used pass because we didn’t want to add any new attributes or methods to the new class. Now, we’re going to add new attributes and methods to a new class. We’ll stick with something similar to our original — our base class. This time around the base class is:
class Person(object):
def __init__(fullName, name): fullName.name = name
def getName(fullName): return fullName.name
def isEmployee(fullName): return False |
We’ve added two new functions above, getName
(to return the full name of the person) and isEmployee
(assuming isEmployee
equals false).
Next, we’ll create a derived class to define that isEmployee
equals True, which looks like this:
class Employee(Person):
def isEmployee(fullName): return True |
So far, we have a class called Person and one called Employee. As you might assume, Person is not an employee, whereas Employee is. You’ll see that in action below with:
emp = Person(“Jack Wallen”) print(emp.getName(), emp.isEmployee())
emp = Employee(“Olivia Nightingale”) print(emp.getName(), emp.isEmployee()) |
You should be able to guess what’s going to happen. Since Jack Wallen is an object of the Person class, they’ll not be listed as an employee, whereas Olivia Nightingale, who is an object of the Employee class, is.
The entire code looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Person(object):
def __init__(fullName, name): fullName.name = name
def getName(fullName): return fullName.name
def isEmployee(fullName): return False
class Employee(Person):
def isEmployee(fullName): return True
emp = Person(“Jack Wallen”) print(emp.getName(), emp.isEmployee())
emp = Employee(“Olivia Nightingale”) print(emp.getName(), emp.isEmployee()) |
Run the above and the output will be:
Jack Wallen False
Olivia Nightingale True
Pretty nifty, eh?
Using the super() Function
There’s also the super()
function, which forces the derived class to inherit all attributes and methods from the base class. This time around, we’re going to focus on students and their graduation year.
The super()
function is used like this:
class Student(Person): def __init__(fullName, fname, lname, year): super().__init__(fname, lname) fullName.graduationyear = year |
The explanation of the super()
function (in the above example) is:
super()
: Returns a temporary object of the superclass that allows the calling of its methods__init__()
: The Python constructor method used for initializing new objects(fname, lname)
: Parameters passed to the superclass constructor
Our entire code looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Person: def __init__(fullName, fname, lname): fullName.firstname = fname fullName.lastname = lname
def printname(fullName): print(fullName.firstname, fullName.lastname)
class Student(Person): def __init__(fullName, fname, lname, year): super().__init__(fname, lname) fullName.graduationyear = year
def welcome(fullName): print(“Welcome”, fullName.firstname, fullName.lastname, “to the class of”, fullName.graduationyear)
x = Student(“Jack”, “Wallen”, 2026) x.welcome() |
Run the above code and the output would be:
Welcome Jack Wallen to the class of 2026
And that’s the basics of Python inheritance. To learn more about inheritance, check out the official Python documentation on the subject.
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don’t miss an episode. Subscribe to our YouTubechannel to stream all our podcasts, interviews, demos, and more.