一入python深似海--class
来源:互联网 发布:linux打开大文件 编辑:程序博客网 时间:2024/04/29 02:00
python class
分为三个部分:class and object(类与对象),inheritance(继承),overload(重载)and override(覆写)。
class and object
类的定义,实例化,及成员访问,顺便提一下python中类均继承于一个叫object的类。
class Song(object):#definition def __init__(self, lyrics): self.lyrics = lyrics#add attribution def sing_me_a_song(self):#methods for line in self.lyrics: print linehappy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"])#object1bulls_on_parade = Song(["They rally around the family", "With pockets full of shells"])#object2happy_bday.sing_me_a_song()#call functionbulls_on_parade.sing_me_a_song()
inheritance(继承)
python支持继承,与多继承,但是一般不建议用多继承,因为不安全哦!
class Parent(object): def implicit(self): print "PARENT implicit()"class Child(Parent): passdad = Parent()son = Child()dad.implicit()son.implicit()
overload(重载)and override(覆写)
重载(overload)和覆盖(override),在C++,Java,C#等静态类型语言类型语言中,这两个概念同时存在。
python虽然是动态类型语言,但也支持重载和覆盖。
但是与C++不同的是,python通过参数默认值来实现函数重载的重要方法。下面将先介绍一个C++中的重载例子,再给出对应的python实现,可以体会一下。
C++函数重载例子:
void f(string str)//输出字符串str 1次{ cout<<str<<endl;}void f(string str,int times)//输出字符串 times次{ for(int i=0;i<times;i++) { cout<<str<<endl; }}
python实现:
通过参数默认值实现重载
<span style="font-size:18px;">def f(str,times=1): print str*timesf('sssss')f('sssss',10)</span>
覆写
class Parent(object): def override(self): print "PARENT override()"class Child(Parent): def override(self): print "CHILD override()"dad = Parent()son = Child()dad.override()son.override()
super()函数
函数被覆写后,如何调用父类的函数呢?
class Parent(object): def altered(self): print "PARENT altered()"class Child(Parent): def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() print "CHILD, AFTER PARENT altered()"dad = Parent()son = Child()dad.altered()son.altered()
python中,子类自动调用父类_init_()函数吗?
答案是否定的,子类需要通过super()函数调用父类的_init_()函数
class Child(Parent): def __init__(self, stuff): self.stuff = stuff super(Child, self).__init__()
9 0
- 一入python深似海--class
- 一入Python深似海--print
- 一入python深似海--split
- 一入python深似海--list
- 一入python深似海--Dict
- 一入python深似海--python之道
- 一入python深似海--函数与文件
- 一入python深似海--变量和对象
- 一入python深似海--正则表达式
- 一入python深似海--tuple和set
- 一入python深似海--对象的属性
- 一入python深似海--目录遍历
- 一入python深似海--小爬虫
- 一入python深似海--变量和对象
- 一入python深似海--what's new in python 3.0
- 一入python深似海--range()、list与for
- 一入python深似海--while-loop与for-loop
- 一入python深似海--dict(字典)的一种实现
- Swift学习 --- 2.3字符串和字符
- 常用ASCII编码表
- Java Reflection - Field
- Java 集合工具类 Collections
- ISCC2014--pwn
- 一入python深似海--class
- 车牌定位--颜色分割
- 漂亮的树形菜单,可折叠,有动画
- 5-word2vec架构分析及实践
- DB2系统级命令及实例级命令
- UVA 10755 Garbage Heap
- 随笔---写在大三下
- Android Studio VS Eclipse (还在用Eclipse?你OUT了!)
- java 内存泄露