您的位置:首页 > 编程语言 > Python开发

python面向对象笔记————持续更新

2019-03-03 14:43 113 查看

面向对象特性

class类:类是对一类有相同属性对象的抽象和概述,在一个类中定义的这些对象都具有相同的属性。

object对象:对象是实例化后的对象,一个类必须经过实列化后才可以在程序中调用,一个类可以实列化多个对象。

encapsulation 封装:类的属性和方法被封装起来,可视但不可修改。

inheritance 继承:一个类可以派生出子类,在这个父类里定义的属性,方法被自动继承。

polymorphism 多态:一个接口,多种实现。

实列化:把一个类变成具体对象的过程叫做实列化。

小列子:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

class cat:
time = 4#类变量
def __init__(self,name,sex,):#构造函数,进行初始化赋值
self.name = name#实例变量(静态属性),作用域是实列本身
self.sex = sex

def eat(self):#类方法(动态属性)
print('I like eat fish')

def catch(self):
print('i can catch the mouse')

print(cat.time)

C1 = cat('花花','female')#实例化一个对象
C1.weight='5'#为实例增加值
print(C1.weight)
C1.catch() #调用方法
# del cat.catch#删除某个方法
# C1.catch()
C1.name ='nb'#修改值
print(C1.name)
C1.time = 5#调用变量时,优先在实例中寻找,若实例中没有则去类变量中寻找,多个实例调用类变量时互不影响。
print(C1.time)

析构函数(- -del- -) 私有方法和私有属性(- -) :

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#析构函数__del__,在实例销毁或者删除后执行,做一些结尾工作
class people:
def __init__(self,name,livel=1000):
self.name = name
self.__livel=livel #私有属性,不可再外部直接访问,但可以通过构造方法来访问

def __del__(self):#最后执行
print('%s have dead'%self.name)

def __got_shut(self):#私有方法
print('i have got shut')

def show_livel(self):
self.__livel -=50
print('%s has %s blood'%(self.name,self.__livel))

P1 = people('jack')

print(P1.show_livel())

P1.got_shut()#若想直接执行__del__,可用del删除实例后执行。

继承(直接代码)

#! /usr/bin/env python
# -*- coding: utf-8 -*-

class animal:#经典类写法
def __init__(self,name,age):
self.name = name
self.age = age

def eat(self):
print('I like eat')

class society(object):#新式类写法
def make(self,obj):
print('%s make frinds _with %s'%(self.name,obj))

class dog(society,animal):#多继承
def bulk(self):
print('i can bulk wang wang wang')

class cat(animal):
def __init__(self,name,age,catchs):
# animal.__init__(self,name,age)#经典方法
super(cat,self).__init__(name,age)#新式类方法
self.catchs = catchs#对构造函数进行修改

def catch(self):
print('i can catch the %s mouse'%self.catchs)

def eat(self):
animal.eat(self)
print('i enjoy the fish')#对父类方法进行修改

d =dog('daxia',2)
d.bulk()

c =cat('huahua',2,5)
c.eat()
c.catch()
d.make(c.name)
#子类之间不可进行调用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: