扩展类 HOW TO EXTEND CLASSES TO MAKE NEW CLASSES IN PYTHON
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/
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.
Open a Python File window.
You see an editor in which you can type the example code.
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.
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的更多相关文章
- tp5自定义扩展类的使用extend
1.在入口index.php定义目录 define('EXTEND_PATH', __DIR__ .'/../extend/'); 2.在使用页引用 use lib\Page; 3.初始化 $page ...
- js深入研究之扩展类,克隆对象,混合类(自定义的extend函数,clone函数,与augment函数)
1.类扩展 /* EditInPlaceField类 */ /* 扩展函数 */ function extend(subClass, superClass) { var F = function() ...
- C# 扩展类
C# 中提供一个非常实用的供能,扩展方法(Extension method) 扩展方法是通过额外的静态方法扩展现有的类型.通过扩展方法,可以对已有类型做自己想做的相关扩展.方法:定义静态类,扩展方法也 ...
- GenericAPIView类与几个扩展类的综合使用
五个扩展类 扩展类 作用 封装的方法 状态码(成功,失败) ListModelMixin 查询多条数据 list 200 CreateModelMixin 新增一条数据 create 201,400 ...
- DRF框架(五)——context传参,二次封装Response类,两个视图基类(APIView/GenericAPIView),视图扩展类(mixins),子类视图(工具视图),视图集(viewsets),工具视图集
复习 1.整体修改与局部修改 # 序列化get (给前端传递参数) #查询 ser_obj = ModelSerializer(model_obj) #只传递一个参数,默认是instance的参数,查 ...
- Dubbo#编译动态扩展类
这篇排版有问题 后面修改....**** 以ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();为例 - ...
- 针对thinkphp 5框架存储过程bug而重写的存储过程的扩展类
近期用tp5框架调取存储过程发现有bug,借鉴了一些官方的函数.以及找了个mysqli的类把存储过程重新写了个扩展类,下面两个类直接放置项目extend目录的stored(这个文件夹名称请按个人习惯命 ...
- tp中调用PHP系统扩展类
例如使用Redis扩展类: use Reids; $redis = new Redis();
- Java+7入门经典 - 6 扩展类与继承 Part 1/2
第6章 扩展类与继承 面向对象编程的一个重要特性: 允许基于已定义的类创建新的类; 6.1 使用已有的类 派生 derivation, 派生类 derived class, 直接子类 direct s ...
随机推荐
- grid 布局 等比例
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
- MATLAB 的字符串分析
MATLAB的字符串分析. 字符串实际上是指1Xn 的字符数组. MATLAB软件具有强大的字符串处理功能,提供了很多的字符或字符串处理函数,包括字符串的创建.字符串的属性.比较.查找以及字符串的转换 ...
- 正确的使用字符串String
字符串作为所有编程语言中使用最频繁的一种基础数据类型.如果使用不慎,将会造成不必要的内存开销,为此而付出代价.而要优化此类型,从以下两点入手: 1.尽量少的装箱 2.避免分配额外的内存空间 先从第一点 ...
- HDU 3085 双广
n*m地图上有 '. ':路 'X':墙 'Z':鬼,每秒蔓延2个单位长度,能够穿墙.共两个,每秒開始时鬼先动 'M':一号,每分钟可移动3个单位长度 'G':二号,每分钟课移动1个单位长度 问两人能 ...
- Centos 7 部署FTP服务简单版
第三方教程推荐与参考: http://blog.csdn.net/somehow1002/article/details/70232791 先安装成功了,有信心了.再进一步扩展配置. 1.安装vsft ...
- AngularCSS 的引入: CSS On-Demand for AngularJS
1) Include the required JavaScript libraries in your index.html (ngRoute and UI Router are optional) ...
- html+css+JavaScript贪吃蛇
写文记录一下最近新完成的贪吃蛇游戏案例,用到了html.css和JavaScript,难度不高,适合刚入坑的同学练习,欢迎大家交流. 下面贴源码: <!DOCTYPE html> < ...
- linux服务器宕机分析/性能瓶颈分析
linux服务器宕机分析/性能瓶颈分析 服务器宕机原因很多,资源不足.应用.硬件.系统内核bug等,以下一个小例子 服务器宕机了,首先得知道服务器宕机的时间点,然后分析日志查找原因 1.last ...
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)什么意思??
从hibernate2.1开始ehcache已经作为hibernate的默认缓存方案(二级缓存方案 sessionfactory级别), 在项目中有针对性的使用缓存将对性能的提升右很大的帮助. 要使用 ...
- php tp验证表单与自动填充函数
<?php class FormModel extends Model { // 自动验证设置 /* * 一:自动验证 自动验证的定义是这样的:array(field,rule,message, ...