扩展类 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 ...
随机推荐
- linux c中select使用技巧——计时器(转)
通过本文你会了解到: 1. select()原型及参数说明 2. select()应用情景 3. select()注意事项 4. select()作定时器 原型 int select(int nfds ...
- Oracle 查询搜索字符串在哪些存储过程中包含
如下: select *from all_source where OWNER = 'LC0019999'and TEXT like '%insert into%d values(%'
- Android创建JSON格式数据
Android创建JSON格式数据 作为上一篇博客的补充,简单那解说了一下Android创建JSON格式数据的小Demo. 1. 创建JSON格式数据 对于Android创建JSON格式数据.因为An ...
- 用尽洪荒之力整理的Mysql数据库32条军规(转)
今天上午吐血整理了Oracle SQL性能优化的40条军规,其中很多规则也是适用于Mysql的,结果今晚发现这一篇文章——用尽洪荒之力整理的Mysql数据库32条军规,和我的竟有异曲同工之妙,当然不同 ...
- 网页中多一些常见效果之伸缩菜单(主要是学习js的书写方法)
效果如下图: 代码很简单,如下: <!doctype html> <html lang="en"> <head> <meta charse ...
- 02-4设置第一启动项--U盘装系统中bios怎么设置USB启动
整个U盘启动里最关键的一步就是设置U盘启动了,本教程内只是以特定型号的电脑为例进行演示,鉴于各种电脑不同BIOS设置U盘启动各有差异,所以如果下面的演示不能适用于你的电脑,建议去百度或者谷歌搜索一下你 ...
- [UIDevice currentDevice].model
iPhone Simulator iPad Simulator iPod touch iPad iPhone
- docker run
1.登录Docker Hub 账户 2.输入命令:构建一个web应用. docker run -d -P training/webapp python app.py 参数说明: -d:让容器在后台运行 ...
- 批量分发SSH秘钥
#!/usr/bin/expect # filename: distribute_key.expif [ $argc != 2 ]{ send_user "usage: expect exp ...
- core image几个滤镜样例 oc版本号和swift版本号
oc版本号 //万花筒模式 + (CGImageRef) getKaleidoscope:(CIContext *)context { CIImage * image = [CIImage image ...