python 的类
来源:互联网 发布:装修招标网源码 编辑:程序博客网 时间:2024/06/04 23:22
1.类的一般形式
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
一般用class关键字来创建一个类,class后面跟类名字,可以自定义,最后以冒号结尾
class ClassName:
'''类的说明'''
类的内容
类的内容可以写类的全局变量等:
案例:
class man(object): #object默认是所有类的父类,不写默认继承object """this is a class""" name = 'zk' age = 30a = man() # 就是把 类man实例化print (type(a))print(a.name)print(a.age)a.age = 20print(a.age)返回的结果为:
<class '__main__.man'>zk3020
#调用类的方法和变量,直接实例化类的后面直接用“.”调用
#如果想给实例a添加变量或者赋值,可以直接用“.”加变量赋值
2.类的构造器
init
__init__ 构造函数,在生成对象时调用。
构造方法init的使用:
class student(object): def __init__(self,name,score): self.name = name self.score = scores = student('kk',90)print (s.name)print (s.score)结果是:
kk90# 在传递参数的时候,必须是传递两个参数,name和score,不然报错
# Self的参数不用传递,python自动会把Student实例化的s传递给第一个参数,即self
3.类的继承
继承类的格式:
class A(父类):
…
多继承
class A: # 定义类 A
.....
class B: # 定义类 B
.....
class C(A, B): # 继承类 A和 B
.....
多继承其实在需要在父类的位置,直接写多个父类就可以,然后用“,”分开就可以了,C类就同时继承了A类和B类。
Python类的继承注意事项:
1. 在继承中类的构造(__init()方法)不会自动调用,它需要在子类的构造中亲自调用。
2. Python总是首先子类中的方法,如果子类没有找到,才回去父类中查找。
案例:class parent: name = 'parent' age = 100 def __init__(self): print 'my name is parent' def get_name(self): return self.name def get_age(self): return self.ageclass child(parent): def __init__(self): print 'I am a child' def hello(self): print 'hello,child'a = child()a.hello()print (a.age)print (a.name)返回的结果:
I am a childhello,child100parent
如果子类没有定义__init__()方法,子类初始化的时候就会调用父类的方法,但是当子类定义了__init__()方法,子类就不会调用父类的__init__()方法,那如果子类想实现父类构造器中的方法,然后自己在写自己特殊的方法呢,这样该怎么办呢?
用super()class parent(object): name = 'parent' age = 100 def __init__(self): print 'my name is parent' def get_name(self): return self.name def get_age(self): return self.ageclass child(parent): def __init__(self): super(child, self).__init__() print ('I am a child') def hello(self): print 'hello child'a = child()a.hello()print (a.age)print (a.name)返回的结果:
my name is parentI am a childhello child100parent
#这里在class parent(object):定义父类的时候,一定要写继承object类,不然那就会有如下的报错信息:TypeError: super() argument 1 must be type, not classobj,增加parent(object)就可以轻松解决。
阅读全文
0 0
- Python--day13 python的类
- 【Python】Python学习笔记(类的继承)
- 【Python】Python的类、对象、属性、方法
- Python--day14 python的类2
- [Python]类的基础知识
- Python的类
- Python类的继承
- python的类
- python类的语法
- Python的类
- Python的str类
- [Python]类的基础知识
- python 类的使用
- python 类的使用
- python类的学习
- Python的类
- [Python]类的基础知识
- python类的继承
- C# 处理进程方法集合
- 基于 Proteus 的单片机仿真
- 排序3
- 两个Java项目之间的通信
- Java
- python 的类
- C语言知识点
- Robot Framework用法总结
- 安卓查询连接wifi的终端型号功能实现(查看蹭网)
- linux I2C驱动调试日志
- java 常用集合list与Set、Map区别及适用场景总结
- 自定义View系列文章目录
- 铜牌汇总2
- Halcon中缩放Region或XLD的方法研究