Home Backend Development Python Tutorial 跟老齐学Python之编写类之四再论继承

跟老齐学Python之编写类之四再论继承

Jun 16, 2016 am 08:41 AM

在上一讲代码的基础上,做进一步修改,成为了如下程序,请看官研习这个程序:

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8

class Person:
    def __init__(self, name, email):
        self.name = name
        self.email = email

class Programmer(Person):
    def __init__(self, name,email,lang, system, website):
        Person.__init__(self,name,email)
        self.lang = lang
        self.system = system
        self.website = website

class Pythoner(Programmer):
    def __init__(self,name,email):
        Programmer.__init__(self,name,email,"python","Ubuntu","qiwsir.github.io")

if __name__=="__main__":
    writer = Pythoner("qiwsir","qiwsir@gmail.com")
    print "name=",writer.name
    print "lang=",writer.lang
    print "email=",writer.email
    print "system=",writer.system
    print "website=",writer.website

#运行结果

name= qiwsir
lang= python
email= qiwsir@gmail.com
system= Ubuntu
website= qiwsir.github.io

 对结果很满意,再看程序中的继承关系:Pythoner

为了能够突出继承问题的探究,还是用那种简单的类来做实验。

多余的B

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8

class A:
    def __init__(self):
        print "aaa"

class B(A):
    pass

if __name__=="__main__":
    a = A()
    b = B()

#运行结果

aaa
aaa

 B继承A,没有任何修改地继承,B就可以不用写任何东西了,或者说B本质上就是一个多余。在真实的编程过程中,没有这样写的,这里仅仅是为了向看官展示一下继承的含义罢了。

复制代码 代码如下:

##首个继承有效

#!/usr/bin/env python
#coding:utf-8

class A:
    def __init__(self):
        print "aaa"

class B:
    def __init__(self):
        print "bbb"

class C1(A,B):
    pass

class C2(B,A):
    pass

if __name__=="__main__":
    print "A--->",
    a = A()
    print "B--->",
    b = B()
    print "C1(A,B)--->",
    c1 = C1()
    print "C2(B,A)--->",
    c2 = C2()

#运行结果

A---> aaa
B---> bbb
C1(A,B)---> aaa
C2(B,A)---> bbb

 列位看官是否注意了,类C1继承了两个类A,B;类C2也继承了两个类,只不过书写顺序有点区别(B,A)。从运行结果可以看出,当子类继承多个父类的时候,对于构造函数__init__(),只有第一个能够被继承,第二个就等掉了。所以,一般情况下,不会在程序中做关于构造函数的同时多个继承,不过可以接力继承,就如同前面那个比较真实的代码一样。

其它方法的继承

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8

class A:
    def __init__(self):
        print "aaa"
    def amethod(self):
        print "method a"

class B(A):
    def __init__(self):
        print "bbb"


if __name__=="__main__":
    print "A--->"
    a = A()
    a.amethod()
    print "B--->"
    b = B()
    b.amethod()

#运行结果

A--->
aaa
method a
B--->
bbb
method a

 为了说明白上面的情况,还是画了一张图,不过,我画完之后,就后悔了,看这张图好像更糊涂了。怎么着也画了,还是贴出来,如果能够协助理解更好了。

A的实例和调用,就不多说了。重点看B,类B继承了A,同时,B在构造函数中自己做了规定,也就是B的构造函数是按照B的意愿执行,不执行A的内容,但是,A还有一个amethod(self)方法,B则继承了这个方法。当通过类B的实例调用这个方法的时候,就能够成功了:b.amethod()

这就是方法的继承和调用方法。

所谓继承,就是从下到上一级一级地找相应的继承对象,找到了就继承之。如果有同名的怎么办?按照什么顺序找呢?

应用网上的一段:

在Python中,可以進行多重繼承,這個時候要注意搜尋的順序,是從子類別開始,接著是同一階層父類別由左至右搜尋,再至更上層同一階層父類別由左至右搜尋,直到達到頂層為止。

代码举例:

复制代码 代码如下:

class A(object):
    def method1(self):
        print('A.method1')

    def method2(self):
        print('A.method2')

class B(A):
    def method3(self):
        print('B.method3')

class C(A):
    def method2(self):
        print('C.method2')

    def method3(self):
        print('C.method3')

class D(B, C):
    def method4(self):
        print('C.method4')

d = D()
d.method4() # 在 D 找到,C.method4
d.method3() # 以 D->B 順序找到,B.method3
d.method2() # 以 D->B->C 順序找到,C.method2
d.method1() # 以 D->B->C->A 順序找到,A.method1

 务必请真正的学习者要对照每个类的每个方法,依次找到相应的输出结果。从而理解继承的顺序。学习,就要点滴积累。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Serialization and Deserialization of Python Objects: Part 1 Serialization and Deserialization of Python Objects: Part 1 Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Mathematical Modules in Python: Statistics Mathematical Modules in Python: Statistics Mar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Mar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python? How to Create Command-Line Interfaces (CLIs) with Python? Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles