How to Extend Classes to Make New Classes in Python - dummies https://www.dummies.com/programming/python/how-to-extend-classes-to-make-new-classes-in-python/

By John Paul Mueller

As you might imagine, creating a fully functional, production-grade class in Python (one that is used in a real-world application actually running on a system that is accessed by users) is time consuming because real classes perform a lot of tasks. Fortunately, Python supports a feature called inheritance. By using inheritance, you can obtain the features you want from a parent class when creating a child class.

Overriding the features that you don’t need and adding new features lets you create new classes relatively fast and with a lot less effort on your part. In addition, because the parent code is already tested, you don’t have to put quite as much effort into ensuring that your new class works as expected.

BUILDING THE CHILD CLASS

Parent classes are normally supersets of something. For example, you might create a parent class named Car and then create child classes of various car types around it.

In this case, you build a parent class named Animal and use it to define a child class named Chicken. Of course, you can easily add other child classes after you have Animal in place, such as a Gorilla class. However, for this example, you build just the one parent and one child class.

class Animal:
def __init__(self, Name=", Age=0, Type="):
self.Name = Name
self.Age = Age
self.Type = Type
def GetName(self):
return self.Name
def SetName(self, Name):
self.Name = Name
def GetAge(self):
return self.Age
def SetAge(self, Age):
self.Age = Age
def GetType(self):
return self.Type
def SetType(self, Type):
self.Type = Type
def __str__(self):
return "{0} is a {1} aged {2}".format(self.Name,
self.Type,
self.Age)
class Chicken(Animal):
def __init__(self, Name=", Age=0):
self.Name = Name
self.Age = Age
self.Type = "Chicken"
def SetType(self, Type):
print("Sorry, {0} will always be a {1}"
.format(self.Name, self.Type))
def MakeSound(self):
print("{0} says Cluck, Cluck, Cluck!".format(self.Name))

The Animal class tracks three characteristics: Name, Age, and Type. A production application would probably track more characteristics, but these characteristics do everything needed for this example. The code also includes the required accessors for each of the characteristics. The __str__() method completes the picture by printing a simple message stating the animal characteristics.

The Chicken class inherits from the Animal class. Notice the use of Animal in parentheses after the Chicken class name. This addition tells Python that Chicken is a kind of Animal, something that will inherit the characteristics of Animal.

Notice that the Chicken constructor accepts only Name and Age. The user doesn’t have to supply a Type value because you already know that it’s a chicken. This new constructor overrides the Animal constructor. The three attributes are still in place, but Type is supplied directly in the Chickenconstructor.

Someone might try something funny, such as setting her chicken up as a gorilla. With this in mind, the Chicken class also overrides the SetType() setter. If someone tries to change the Chicken type, that user gets a message rather than the attempted change. Normally, you handle this sort of problem by using an exception, but the message works better for this example by making the coding technique clearer.

Finally, the Chicken class adds a new feature, MakeSound(). Whenever someone wants to hear the sound a chicken makes, he can call MakeSound() to at least see it printed on the screen.

TESTING THE CLASS IN AN APPLICATION

Testing the Chicken class also tests the Animal class to some extent. Some functionality is different, but some classes aren’t really meant to be used. The Animal class is simply a parent for specific kinds of animals, such as Chicken. The following steps demonstrate the Chicken class so that you can see how inheritance works.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    import Animals
    MyChicken = Animals.Chicken("Sally", 2)
    print(MyChicken)
    MyChicken.SetAge(MyChicken.GetAge() + 1)
    print(MyChicken)
    MyChicken.SetType("Gorilla")
    print(MyChicken)
    MyChicken.MakeSound()

    The first step is to import the Animals module. Remember that you always import the filename, not the class. The Animals.py file actually contains two classes in this case: Animal and Chicken.

    The example creates a chicken, MyChicken, named Sally, who is age 2. It then starts to work with MyChicken in various ways.

    For example, Sally has a birthday, so the code updates Sally’s age by 1. Notice how the code combines the use of a setter, SetAge(), with a getter, GetAge(), to perform the task. After each change, the code displays the resulting object values for you. The final step is to let Sally say a few words.

  3. Choose Run→Run Module.

    You see each of the steps used to work with MyChicken. As you can see, using inheritance can greatly simplify the task of creating new classes when enough of the classes have commonality so that you can create a parent class that contains some amount of the code.

https://stackoverflow.com/questions/15374857/should-all-python-classes-extend-object

python继承(二)extends - baiyan_er的博客 - CSDN博客 https://blog.csdn.net/baiyan_er/article/details/78935451

class car(object):
def __init__(self, brand, color):
self.brand = brand
self.color = color def run(self):
print('A car is running.', self.brand, self.color) class SUV(car):
def __init__(self, brand, color, seats):
car.brand = brand
car.color = color
self.seats = seats def run(self):
print('A SUV is runnung.', self.brand, self.color, self.seats) aCar = car('carBrand', 'red')
aCar.run()
aSUV = SUV('suvBrand', 'black', 5)
aSUV.run()

A car is running. carBrand red
A SUV is runnung. suvBrand black 5

方法重写:子类继承父类时,子类的方法签名和父类一样,此时子类重写了父类的方法,当生成子类对象时,调用的是子类重写的方法
class car(object):
def __init__(self,brand,color):
self.brand=brand
self.color=color
def run(self):
print("汽车在公路上行驶...")
class suv(car):
def __init__(self,brand,color,seats):
car.brand=brand
car.color=color
self.seats=seats
def run(self):
print("suv汽车在公路上行驶...")
suv=suv("奔驰","黑色",5)
suv.run()
# 子类和父类的方法名子是一样的方法的重写

  

多继承:类同时继承多个父类,class c(A,B),iv e AB均有相同方法,而子类又得写时,调用写在前面的方法,如果子类没有方法,则调用自己前面的方法

可以通过:类名 . __mro__  输出类的访问顺序

class A(object):
def test(self):
print("......A........")
class B(object):
def test(self):
print("......B........")
class C(A,B):
def test(self):
super().test()
print("......C........") c=C()
c.test()
print(C.__mro__)

  

 

扩展类 HOW TO EXTEND CLASSES TO MAKE NEW CLASSES IN PYTHON的更多相关文章

  1. tp5自定义扩展类的使用extend

    1.在入口index.php定义目录 define('EXTEND_PATH', __DIR__ .'/../extend/'); 2.在使用页引用 use lib\Page; 3.初始化 $page ...

  2. js深入研究之扩展类,克隆对象,混合类(自定义的extend函数,clone函数,与augment函数)

    1.类扩展 /* EditInPlaceField类 */ /* 扩展函数 */ function extend(subClass, superClass) { var F = function() ...

  3. C# 扩展类

    C# 中提供一个非常实用的供能,扩展方法(Extension method) 扩展方法是通过额外的静态方法扩展现有的类型.通过扩展方法,可以对已有类型做自己想做的相关扩展.方法:定义静态类,扩展方法也 ...

  4. GenericAPIView类与几个扩展类的综合使用

    五个扩展类 扩展类 作用 封装的方法 状态码(成功,失败) ListModelMixin 查询多条数据 list 200 CreateModelMixin 新增一条数据 create 201,400 ...

  5. DRF框架(五)——context传参,二次封装Response类,两个视图基类(APIView/GenericAPIView),视图扩展类(mixins),子类视图(工具视图),视图集(viewsets),工具视图集

    复习 1.整体修改与局部修改 # 序列化get (给前端传递参数) #查询 ser_obj = ModelSerializer(model_obj) #只传递一个参数,默认是instance的参数,查 ...

  6. Dubbo#编译动态扩展类

    这篇排版有问题 后面修改....**** 以ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();为例 - ...

  7. 针对thinkphp 5框架存储过程bug而重写的存储过程的扩展类

    近期用tp5框架调取存储过程发现有bug,借鉴了一些官方的函数.以及找了个mysqli的类把存储过程重新写了个扩展类,下面两个类直接放置项目extend目录的stored(这个文件夹名称请按个人习惯命 ...

  8. tp中调用PHP系统扩展类

    例如使用Redis扩展类: use Reids; $redis = new Redis();

  9. Java+7入门经典 - 6 扩展类与继承 Part 1/2

    第6章 扩展类与继承 面向对象编程的一个重要特性: 允许基于已定义的类创建新的类; 6.1 使用已有的类 派生 derivation, 派生类 derived class, 直接子类 direct s ...

随机推荐

  1. 《windows核心编程》- 线程栈

    当系统创建线程的时候,会为线程栈预订一块地址空间区域,并给该区域调拨一些物理存储器.默认会预订1MB的地址空间并调拨两个页面的存储器.但是在构建 应用程序的时候可以改变这个默认值 在构建应用程序的时候 ...

  2. js ctrl+v实现图片粘贴

    <script> // demo 程序将粘贴事件绑定到 document 上 document.addEventListener("paste", function ( ...

  3. rac_安装软件时报版本号过高问题

    原创作品,出自 "深蓝的blog" 博客.欢迎转载,转载时请务必注明下面出处,否则追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlo ...

  4. springboot学习(四) 日志管理

    1.简介 Spring Boot内部日志系统使用的是Commons Logging,但开放底层的日志实现.默认为会Java Util Logging, Log4J, Log4J2和Logback提供配 ...

  5. Silverlight实例教程 - Validation数据验证基础属性和事件(转载)

    Silverlight 4 Validation验证实例系列 Silverlight实例教程 - Validation数据验证开篇 Silverlight实例教程 - Validation数据验证基础 ...

  6. Linux学习之inode说明

    硬盘是常见的存储设备,最小单位叫做扇区,大小512kb. 文件存储在硬盘中,文件存储最小单位叫做块,大小通常为4k. iNode用于存放文件的元信息,元信息如下: 所有者 所有组 权限 时间戳,cti ...

  7. Python内置函数之any()

    any()函数和all()函数相对立. 相同点为: any()也只能传入一个参数. any()的参数必须是可迭代对象. 不同点: 可迭代对象中只要有一个元素为True,返回值就是True. 下面看看具 ...

  8. D - Sigma Function 1~n内有多少个约数和为偶数

    /** 题目:D - Sigma Function 链接:https://vjudge.net/contest/154246#problem/D 题意:求1~n内约数和为偶数的数的个数. 思路:一个数 ...

  9. zeppelin部署

    1.下载解压2.修改conf/zeppelin-env.sh,添加如下两行 export ZEPPELIN_PORT= export MASTER=spark://master:7077 3.启动 b ...

  10. Mybatis在IDEA中使用generator逆向工程生成pojo,mapper

    使用mybatis可以逆向生成pojo和mapper文件有很多种方式,我以前用的是mybtais自带的generator包来生成,连接如下:mybatis自己生成pojo 今天我用了IDEA上使用ma ...