python之面向对象
说到面向对象,必然有类,对象,方法,变量等概念。
得到对象
要有对象,首先要有类,然后将类实例化成一个对象。
class Test:
#定义基本属性
name = ''
#定义私有属性,私有属性在类外部无法直接进行访问
#__name = ''
#定义构造方法
def __init__(self, name):
self.name = name
def printf(self):
print(self.name)
#定义私有方法,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__printf
#def __printf(self):
# print(self.name)
class 关键字用于声明一个类,而def用于声明一个方法。
python的类中有一些专有方法,__init__就是其中一个,它类似于java中的构造方法,用于初始化。
self
可以发现__init__第一个参数是self。self代表类的实例,而非类。只要是类方法,它的第一个参数都是self,并非专有方法独有。java中通过new关键字实例化类。而python中省去了new
test = Test('xxx') #实例化
test.printf() #调用printf方法
继承
即子类得到父类的属性及方法
java不支持多继承,而python支持
- 单继承
#父类 class Father: #定义基本属性 name = '' #定义构造方法 def __init__(self,name): self.name = name def printf(self): print(self.name) #单继承 class Son(Father): age = 0 def __init__(self,name, age): #调用父类的构造方法 Father.__init__(self,name) self.age = age
- 多继承
多继承中,对于父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索,即方法在子类中未找到时,从左到右(圆括号中顺序)查找父类中是否包含方法。#父类 1 class Father: #定义基本属性 name = '' #定义构造方法 def __init__(self,name): self.name = name def printf(self): print(self.name) #父类 2 class Mother: #定义基本属性 weight = 0 #定义构造方法 def __init__(self,weight): self.weight = weight def printf(self): print(self.weight) #单继承 class Son(Father, Mother): age = 0 def __init__(self,name, age, weight): #调用父类的构造方法 Father.__init__(self,name) Mother.__init__(self,weight) self.age = age
重写
继承父类方法时,子类可重写父类方法
#父类
class Father:
#定义基本属性
name = ''
#定义构造方法
def __init__(self,name):
self.name = name
def printf(self):
print(self.name)
#单继承
class Son(Father):
age = 0
def __init__(self,name, age):
#调用父类的构造方法
Father.__init__(self,name)
self.age = age
def printf(self):#重写父类方法
print(self.age)
father = Father('father')
son = Son('son', 18)
father.printf()#father
son.printf()#18
类的专有方法
- _init_ : 构造函数,在生成对象时调用
- _del_ : 析构函数,释放对象时使用
- _repr_ : 打印,转换
- _setitem_ : 按照索引赋值
- _getitem_: 按照索引获取值
- _len_: 获得长度
- _cmp_: 比较运算
- _call_: 函数调用
- _add_: 加运算
- _sub_: 减运算
- _mul_: 乘运算
- _truediv_: 除运算
- _mod_: 求余运算
- _pow_: 乘方