面向对象编程的三大特性:封装性,继承性,多态性
python创建类的标准格式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Animal: num=0 #类变量 def __init__(self,aname,acolor): #构造方法 self.name=aname #成员变量 self.color=acolor def show(self): print("名字:{},颜色:{},数量:{}".format(self.name,self.color,Animal.num)) ani1 = Animal("fish","white") #创建Animal的实例对象 ani2 = Animal("bird","green") ani1.show() ani2.show() Animal.num=2 #通过类名来赋值 ani1.show() ani2.show()
1
2
3
4名字:fish,颜色:white,数量:0 名字:bird,颜色:green,数量:0 名字:fish,颜色:white,数量:2 名字:bird,颜色:green,数量:2
1.类是描述一组对象的共同特征(成员变量)和行为(方法),在创建对象之前要定义一个类。
2.创建对象时,就会自动为新生成的对象调用构造方法。
1
2
3
4
5
6
7
8
9
10class Dog: ...... def show(self,weight): print("重量{}".format(weight)) print("颜色{}".format(self.color)) dog = Dog(color="grey") dog.weight = 52 #添加构造方法中没有的属性,在show方法中添加参数weight dog.show(dog.weight)
3.添加属性,调用该方法
构造方法&析构方法
1
2
3
4
5
6
7
8
9
10
11
12
13#无参构造方法 def __init__(self): self.attribute = "string" #有参构造方法 def __init(self, attri1= "",attri2=""): self.attri1=attri1 self.attri2=attri2 #析构方法 def __del__(self): print("Object deleted")
1.未定义构造方法,python会自动提供一个默认的构造方法
2.使用del objects语句可以自动调用析构方法
成员变量和类变量&类方法和静态方法
1.成员方法在构造方法中定义的,类变量在类中方法之外定义
2.成员变量只能通过对象名访问,类变量属于类,通过对象名和类名访问
1
2
3
4
5
6
7
8
9
10
11
12
13@classmethod #修饰器 def classmethod(cls): print("class method") def get_date(cls,string_date): year,month,day = map(int, string_date.split('-')) #通过map函数把年月日以-分开并转为int类型 date1 = cls(year,month,day) cls().m() #通过此方式调用m方法 return date1 #返回初始化的类
3.修饰器@classmethod装饰的类方法
1
2
3
4@staticmethod def staticmethod(): print("static method")
4.修饰器@staticmethod来标识静态方法,可以通过对象名和类名调用
5.self的意思为对象本身
6.cls的意思为调用当前的类名,在类方法中调用
类的继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Animal: num=0 def __init__(self): print("父类Animal") def show(self): print("父类Animal成员方法") class Cat(Animal): def __init__(self): print("构建子类Cat") def run(self): print("子类cat成员方法") cat = Cat() cat.run() #子类方法 cat.show() #父类方法
1
2
3
4构建子类Cat 子类cat成员方法 父类Animal成员方法 [Finished in 205ms]
1.Cat属于Animal类,自动拥有Animal类所有可继承的属性和方法,而且可直接通过cat对象名调用父类和子类方法
1
2
3
4
5
6
7
8
9
10
11
12
13#私有属性 & 私有方法 class Employee: def __init(self,name="",department="computer"): self.setName(name) self.setDedpartment(department) #通过调用方法,实现对对象的私有属性进行控制 def setName(self,name): if(type(name)!=str): print("姓名必须是字符") return self.__name = name # __name这样的形式为私有属性
2.以两个下划线"__"开头的属性是私有属性,只能在类的内部访问,类外部不能直接访问,可以实现类的封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Animal: def __init__(self, isAnimal): self.isAnimal = isAnimal def run(self): print("父类的Animal通用的run()方法") def show(self): print("父类Animal的show()方法") class Cat(Animal): def __init__(self): print("子类的构造方法") def run(self): super().run() #使用super()方法调用父类的方法 print("子类cat重写的run()方法") ani = Animal(False) ani.show() cat = Cat() cat.run()
1
2
3
4
5父类Animal的show()方法 子类的构造方法 父类的Animal通用的run()方法 子类cat重写的run()方法 [Finished in 255ms]
3.方法重写:父类定义的方法不能满足子类的需求,子类可以按照自己的方式重新定义,但子类中重写的方法要与父类中的具有相同的方法名和参数列表;super()方法主要用于在继承过程中访问父类的成员
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Phone: #电话类 def recieve(self): print("接电话") def send(self): print("打电话") class Message: #消息类 def recieveMsg(self): print("接收短信") def sendMsg(self): print("发送短信") class Mobile(Phone, Message): #手机类 pass mobile = Mobile() mobile.recieve() mobile.send() mobile.recieveMsg() mobile.sendMsg()
1
2
3
4
5接电话 打电话 接收短信 发送短信 [Finished in 210ms]
4.python的多继承: 子类(父类1,父类2)的形式来定义多继承的子类
类的多态
同一种方法(方法名相同),由于参数类型或参数个数的不同而导致执行效果各异的现象就是多态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Animal: def __init__(self,aname): self.name = aname def enjoy(self): print("nangnang") class Cat(Animal): def enjoy(self): #根据猫的特征重写父类enjoy方法 print(self.name,"miaomiao") class Dog(Animal): def enjoy(self): #根据狗的特征重写父类enjoy方法 print(self.name+"wangwang") class Person: def __init__(self,id,name): self.name = name self.id = id def drive(self, ani): #接受一个参数,根据对象的归属不同调用不同的方法 ani.enjoy() cat = Cat("Mikey") dog = Dog("dahuang ") person = Person("zhang3",9) person.drive(cat) person.drive(dog)
1
2
3Mikey miaomiao dahuang wangwang [Finished in 209ms]
1.Person类中drive中根据驱赶动物的不同调用相应方法
运算符重载
为了能在一些对象上(列表,元组,自定义)上使用+,-,*,/等运算符,对每个运算符对应的指定内置方法进行修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38#加法和减法运算符重载 class Computing: def __init__(self, value): #类Computing的属性value是一个数值列表 self.value = value def __add__(self,other): #对列表中每个元素进行+other的操作 lst = [] for i in self.value: lst.append(i+other) return lst def __sub__(self, other): lst = [] for i in self.value: lst.append(i-other) return lst c = Computing([-1,3,4,5]) print("+运算符重载后的列表:",c+2) print("-运算符重载后的列表:",c-2) #__str__()和__ge__()方法重载 class Stundent: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "{} {}".format(self.name, self.age) def __ge__(self,obj): if self.age >= obj.age: return True return False s1 = Stundent("Rose",17) s2 = Stundent("John",19) print("学生s1:",s1) print("学生s2:",s2) print("学生大小的比较:",s1>=s2)
1
2
3
4
5
6+运算符重载后的列表: [1, 5, 6, 7] -运算符重载后的列表: [-3, 1, 2, 3] 学生s1: Rose 17 学生s2: John 19 学生大小的比较: False [Finished in 212ms]
1.repr() 函数将对象转化为供解释器读取的形式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#索引和切片重载 class SelectData: def __init__(self, data): self.data = data[:] def __getitem__(self, index): return self.data[index] def __setitem__(self,index,value): self.data[index] = value def __delitem__(self,index): del self.data[index] x = SelectData([12,33,23,"ab",False]) print(x) print(x[:]) print(x[2]) print(x[2:]) x[4]=100 print(x[:]) del(x[3]) for num in x: print(num, end=" ")
1
2
3
4
5
6<__main__.SelectData object at 0x000002BDEB9C1FD0> [12, 33, 23, 'ab', False] 23 [23, 'ab', False] [12, 33, 23, 'ab', 100] 12 33 23 100 [Finished in 215ms]
2.__getitem__方法用于所引和切片,__setitem__用于索引赋值,__delitem__用于使用del关键字删除对象
参考:
·python3程序设计 “十三五”规划教材
最后
以上就是柔弱钢铁侠最近收集整理的关于python面向对象学习--1的全部内容,更多相关python面向对象学习--1内容请搜索靠谱客的其他文章。
发表评论 取消回复