Intro
类是指描述每个对象包含的数据和特征的一种数据类型。类由变量和函数两部分构成,类中的变量称之为成员变量,类中的函数称之为成员函数。类是客观世界中事物的抽象,而对象是类实例化后的变量。例如,汽车模型可以制造出不同的骑车,每辆汽车就是一个对象。汽车模型是对汽车特征和行为的抽象,而汽车是实际存在的事物,是客观世界中实实在在的实体。因此,根据类的定义可以构造出许多对象。
Knowledge
类:python使用class保留字定义一个类,类名的首字母一般要大写。类把需要使用的变量和函数组合在一起,称之为封装。
对象:类实例化后的变量。创建对象的过程称之为实例化,包含对象的句柄、属性和方法。对象的句柄用于区分不同的对象,当对象被创建后,该对象会获取一块存储空间,存储空间的地址即为对象的标识。对象的属性和方法与类的成员变量和成员函数相对应。(python中的任何类型都是对象,包括字符串类型、数字类型、内置数据结构等。)
经典对象:内部由属性和方法组成。属性可以是数据类型,也可以是函数类型。
新型对象:新型对象内建了object对象,该对象是内建类型和新型对象的父类,或称为基类。object也可以看做是对象。如果要定义新型类型,必须继承object对象。
私有属性:类的私有属性不能被该类之外的函数调用,常在名字下以像个下划线表示(__ID)。
公有属性:类的公有属性可以被该类之外的函数调用,一般没有使用两个下划线。
实例属性:以self作为前缀的属性,如果__init__方法中定义的变量没有使用self作为前缀声明,则该变量为普通的局部变量。类中其他方法定义的变量也只是局部变量,而非类的实例属性。
静态属性:可以被类直接调用而不被实例化对象调用的属性。当创建新的实例化对象后,静态变量并不会获得新的内存空间,而是使用类创建后静态变量的空间。因此,静态变量能够被多个实例化对象共享。在python中静态变量称之为静态属性。
私有方法:不能被该类之外的函数调用的方法。
公有方法:可以被该类之外的函数调用的方法。
静态方法:python使用函数statucmethod()或@statucmethod指令的方式将普通的函数转换为静态的方法,属于全局函数。
类方法:类方法必须提供self,可以使用classmethod()或@classmethod指令定义。
内部类:在某个类内部定义的类。内部类容易造成程序结构的复杂,不提倡使用。
__init__方法:构造函数,用于初始化类的内部状态,为类的属性设置默认值。也可用于程序的初始化。
__del__方法:析构函数用于释放对象占用的资源。
__new__方法:在__init__之前被调用,用于生成实例对象,可以实现设计模式中的单例模式。
单例模式:指创建唯一对象,单例模式设计的类智能实例化1个对象。
垃圾回收机制:python提供gc模块释放不再使用的对象。垃圾回收机制有许多种算法,python采用的是引用计数的方式。当某个对象在其作用域内不再被其他对象引用时,python就会自动清除该对象。函数collect()可以一次性收集所有待处理的对象。
继承:继承是相对两个类而言的父子关系,子类继承了父类所有的公有实例变量和方法。
抽象类:对一类事物的特征和行为的抽象,抽象类由抽象方法组成。
多态性:是指发出同样的消息被不同类型的对象接收时,有可能导致完全不同的行为,即在用户不作任何干预的环境下,类的成员函数的行为能根据调用它的对象类型自动作出适应性调整,而且调整是发生在程序运行时。由于python的动态类型,决定了python的多态性。
多重继承:即1个类可以继承多个父类。
运算符的重载:实现对象之间的运算。python把运算符和类的内置方法关联起来,每个运算符都对应1个函数。
设计模式:是面向对象程序设计的解决方案,是复用性程序设计的经验总结。设计模式的目标是形成典型问题的解决方案,设计出可复用的软件结构。根据使用目的的不同分为创建型模式、结构型模式和行为型模式。
创建型模式:提出了对象创建的解决方案以及数据封装的方法。如工厂模式、单例模式、生成器模式等。
结构型模式:描述了对象之间的体系结构,通过组合、继承等方式改善体系结构,降低体系结构中组件的依赖性。如适配器模式、桥模式、组合模式、装饰器模式、外观模式等。
行为型模式:描述了对象之间的交互和各自的职责,有助于实现程序中对象的通讯和流程的控制。如迭代器模式、解释器模式、中介者模式、观察者模式等。
Apply
apply1:类、对象的创建及其属性方法的调用
#定义一个类Person
class Person(object):
def __init__(self,name,age,sex):
self.name = name
self.age=age
self.sex=sex
def walk(self):
print('person can walk')
def run(self):
print('person can run')
#对象的创建以及类属性和方法的调用
xiaoming=Person('小明','25','male')
print(xiaoming.name)
print(xiaoming.age)
print(xiaoming.sex)
xiaoming.walk()
xiaoming.run()
apply2:实例属性
#定义一个类Person
class Fruit:
price=0 #类属性
def __init__(self):
self.color= 'red' #实例属性
zone='chaina'#局部变量
print(Fruit.price)
apple=Fruit()
print(apple.color)
Fruit.price=Fruit.price+10
print('apple\'s prince:',str(apple.price))
banana=Fruit()
print('banana\'s price',str(banana.price))
apply3:私有属性
#定义一个类Person
class Fruit:
price=0 #类属性
def __init__(self):
self.__color= 'red' #私有属性
zone='chaina'#局部变量
print(Fruit.price)
apple=Fruit()
print(apple.color)
Fruit.price=Fruit.price+10
print('apple\'s prince:',str(apple.price))
banana=Fruit()
print('banana\'s price',str(banana.price))
apply4:静态方法
#定义一个类Person
class Fruit:
price=0 #类属性
def __init__(self):
self.__color= 'red' #私有属性
def getcolor(self):
print(self.__color)
@staticmethod # 静态方法
def getprice():
print(Fruit.price)
def __getprice():
Fruit.price = Fruit.price+10
print(Fruit.price)
count=staticmethod(__getprice) #静态方法
apple=Fruit()
apple.getcolor()
Fruit.count()
banana=Fruit()
Fruit.count()
Fruit.getprice()
apply5:类方法
#定义一个类Person
class Fruit:
price=0 #类属性
def __init__(self):
self.__color= 'red' #私有属性
def getcolor(self):
print(self.__color)
@classmethod # 类方法
def getprice(self):
print(self.price)
def __getprice(self):
self.price = self.price+10
print(self.price)
count=classmethod(__getprice) #类方法
apple=Fruit()
apple.getcolor()
Fruit.count()
banana=Fruit()
Fruit.count()
Fruit.getprice()
apply6:内部类的使用
#内部类的使用
class Fruit:
class Color:
def color(self):
print('red')
class Price:
def price(self):
self.price=self.price+10
print(self.price)
#外部类实例化
apple=Fruit()
#直接使用外部类调用内部类,生成内部类实例,再调用内部类方法
apple_color1=Fruit.Color()
#先对外部类进行实例化,再实例化内部类,最后调用内部类方法
apple_color2=apple.Color()
#调用内部类方法
apple_color1.color()
apple_color2.color()
apply7:析构函数
#析构函数
class Fruit:
def __init__(self,color):
self.__color = color
print(self.__color)
def __del__(self):
self.__color=''
print('free...')
def grow(self):
print('gtow...')
color='red'
fruit=Fruit(color)
fruit.grow()
del fruit #显示调用析构函数,若不调用,python会自动执行
apply8:单例模式的实现
class Singleton(object):
__instance=None #定义实例
def __init__(self):
pass
def __new__(cls, *args, **kwargs):#在__init__之前调用
if Singleton.__instance is None:#生成唯一实例
Singleton.__instance=object.__new__(cls, *args, **kwargs)
return Singleton.__instance
apply9:类方法的动态添加(类的动态性)
class Fruit:
pass
def add(self):
print('grow...')
Fruit.grow=add#添加类方法并命名为grow
fruit = Fruit()
fruit.grow()
apply10:继承的实现(类的继承性)
class Fruit:
def __init__(self,color):
self.color=color
print(self.color)
def grow(self):
print('grow...')
class Apple(Fruit):
def __init__(self,color):
Fruit.__init__(self,color)
print(self.color)
class Banana(Fruit):
def __init__(self,color):
Fruit.__init__(self,color)
print(self.color)
def grow(self):
print('banana grow...')
apple=Apple('red')
apple.grow()
banana=Banana('bule')
banana.grow()
apply11:super()调用父类__init__方法
class Fruit:
def __init__(self,color):
self.color=color
print(self.color)
def grow(self):
print('grow...')
class Apple(Fruit):
def __init__(self,color):
super(Apple,self).__init__(color)
Apple('red')
apply12:抽象类(Fruit)
def abstract():
raise NotADirectoryError('abstract')
class Fruit:
def __init__(self):
if self.__class__ is Fruit:
abstract()
print('Fruit')
class Apple(Fruit):
def __init__(self):
super(Apple,self).__init__()
print('Apple')
apple=Apple()
fruit = Fruit()
apply13:类的多态性
class Fruit:
def __init__(self,color=None):
self.color=color
class Apple(Fruit):
def __init__(self,color='red'):
Fruit.__init__(self,color)
class Banana(Fruit):
def __init__(self,color='yellow'):
Fruit.__init__(self,color)
class Fruitshop:
def sellFruit(self,fruit):
if isinstance(fruit,Apple):
print('sell Apple')
if isinstance(fruit,Banana):
print('sell Banana')
if isinstance(fruit,Fruit):
print('sell fruit')
shop=Fruitshop()
apple=Apple('red')
banana=Banana('Yello')
shop.sellFruit(apple)#参数的多态性,传入apple对象
shop.sellFruit(banana)#参数的多态性,传入banana对象
apply14:类的多重继承
#继承体系结构分为3层:父类object层、水果分类层和水果层。减少了继承的层次,同时把依赖关系移到了分类层,方便以后新增新的类别。
class Fruit(object):
def __init__(self):
pass
class HuakedFruit(object):
def __init__(self):
print('HuakedFruit')
def husk(self):
print('husk...')
class DecorticatedFruit(object):
def __init__(self):
print('DecorticatedFruit')
def decorticat(self):
print('decorticat...')
class Apple(HuakedFruit,Fruit):
pass
class Banana(DecorticatedFruit,Fruit):
pass
apply15:运算符的重载
class Fruit():
def __init__(self,price=0):
self.price = price
def __add__(self, other):
return self.price + other.price
def __gt__(self, other):
if self.price > other.price:
flag =True
else:
flag = False
return flag
class Apple(Fruit):
pass
class Banana(Fruit):
pass
apple= Apple(5)
print('苹果的价格:',apple.price)
banana= Banana(8)
print('香蕉的价格:',banana.price)
total=apple+banana
print('合计:',total)
apply16:工厂方法的实现
class Factory:
def createFruit(self,fruit):
if fruit=='apple':
return Apple()
elif fruit=='banana':
return Banana()
class Fruit():
def __str__(self):
return 'fruit'
class Apple(Fruit):
def __str__(self):
return 'apple'
class Banana(Fruit):
def __str__(self):
return 'banana'
factory=Factory()
apple= Apple()
banana= Banana()
print(factory.createFruit('apple'))#创建对象apple
print(factory.createFruit('banana'))#创建对象banana
Result
apply1:
小明
25
male
person can walk
person can run
apply2:
red
apple's prince: 10
banana's price 10
apply3:
AttributeError: 'Fruit' object has no attribute 'color'
apply4:
red
10
20
20
apply5:
red
10
20
20
aplly6:
red
red
apply7:
red
gtow...
free...
apply8:
无输出结果
apply9:
grow...
apply10:
red
red
grow...
bule
bule
banana grow...
apply11:
red
apply12:
Fruit
Apple
raise NotADirectoryError('abstract')
NotADirectoryError: abstract
apply13:
sell Apple
sell fruit
sell Banana
sell fruit
apply14:
无输出结果
apply15:
苹果的价格: 5
香蕉的价格: 8
合计: 13
apply16:
apple
banana
领取专属 10元无门槛券
私享最新 技术干货