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

Python基础-封装与扩展、静态方法和类方法

2017-04-23 12:02 441 查看

一、封装与扩展

封装在于明确区分内外,使得类实现者可以修改封装内的东西而不影响外部调用者的代码;而外部使用者只知道一个接口(函数),只要接口(函数)名、参数不变,使用者的代码永远无需改变。这就提供一个良好的合作基础——或者说,只要接口这个基础约定不变,则代码改变不足为虑。 

实例:

1 #类的设计者
2 class Room:
3     def __init__(self,name,owner,width,length,high):
4         self.name=name
5         self.owner=owner
6         self.__width=width    #私有属性,对外封闭,类的内部可以调用
7         self.__length=length
8         self.__high=high
9
10     def tell_area(self): #对外提供的接口,隐藏了内部的实现细节,此时我们想求的是面积
11         return self.__width * self.__length
1 #使用者
2 >>> r1=Room('卧室','egon',20,20,20)
3 >>> r1.tell_area() #使用者调用接口tell_area
4 400
1 #类的设计者,轻松的扩展了功能,而类的使用者完全不需要改变自己的代码
2 class Room:
3     def __init__(self,name,owner,width,length,high):
4         self.name=name
5         self.owner=owner
6         self.__width=width
7         self.__length=length
8         self.__high=high
9
10     def tell_area(self): #对外提供的接口,隐藏内部实现,此时我们想求的是体积,内部逻辑变了,只需修改下列一行就可以很简单的实现,而且外部调用感知不到,仍然使用该方法,但是功能已经变了
11         return self.__width * self.__length * self.__high
1 #对于仍然在使用tell_area接口的人来说,根本无需改动自己的代码,就可以用上新功能
2 >>> r1.tell_area()
3 8000

二、静态方法和类方法

通常情况下,在类中定义的所有函数(注意了,这里说的就是所有,跟self啥的没关系,self也只是一个再普通不过的参数而已)都是对象的绑定方法,对象在调用绑定方法时会自动将自己作为参数传递给方法的第一个参数。除此之外还有两种常见的方法:静态方法和类方法,二者是为类量身定制的,但是实例非要使用,也不会报错,后续将介绍。

1. 静态方法

是一种普通函数,位于类定义的命名空间中,不会对任何实例类型进行操作,python为我们内置了函数staticmethod来把类中的函数定义成静态方法

1 class Foo:
2     def spam(x,y,z): #类中的一个函数,千万不要懵逼,self和x啥的没有不同都是参数名
3         print(x,y,z)
4     spam=staticmethod(spam) #把spam函数做成静态方法

基于之前所学装饰器的知识,@staticmethod 等同于spam=staticmethod(spam),于是

1 class Foo:
2     @staticmethod #装饰器
3     def spam(x,y,z):
4         print(x,y,z)

使用演示

1 print(type(Foo.spam)) #类型本质就是函数
2 Foo.spam(1,2,3) #调用函数应该有几个参数就传几个参数
3
4 f1=Foo()
5 f1.spam(3,3,3) #实例也可以使用,但通常静态方法都是给类用的,实例在使用时丧失了自动传值的机制
6
7 '''
8 <class 'function'>
9 1 2 3
10 3 3 3
11 '''

应用场景:编写类时需要采用很多不同的方式来创建实例,而我们只有一个__init__函数,此时静态方法就派上用场了

1 class Date:
2     def __init__(self,year,month,day):
3         self.year=year
4         self.month=month
5         self.day=day
6
7    @staticmethod
8     def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间
9         t=time.localtime() #获取结构化的时间格式
10         return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
11
12     @staticmethod
13     def tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
14         t=time.localtime(time.time()+86400)
15         return Date(t.tm_year,t.tm_mon,t.tm_mday)
16
17 a=Date('1987',11,27) #自己定义时间
18 b=Date.now() #采用当前时间
19 c=Date.tomorrow() #采用明天的时间
20
21 print(a.year,a.month,a.day)
22 print(b.year,b.month,b.day)
23 print(c.year,c.month,c.day)

2. 类方法

类方法是给类用的,类在使用时会将类本身当做参数传给类方法的第一个参数,python为我们内置了函数classmethod来把类中的函数定义成类方法

1 class A:
2     x=1
3     @classmethod
4     def test(cls):
5         print(cls,cls.x)
6
7 class B(A):
8     x=2
9 B.test()
10
11 '''
12 输出结果:
13 <class '__main__.B'> 2
14 '''

应用场景

1 import time
2 class Date:
3     def __init__(self,year,month,day):
4         self.year=year
5         self.month=month
6         self.day=day
7
8    @staticmethod
9     def now():
10         t=time.localtime()
11         return Date(t.tm_year,t.tm_mon,t.tm_mday)
12
13 class EuroDate(Date):
14     def __str__(self):
15         return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)
16
17 e=EuroDate.now()
18
19 print(e) #我们的意图是想触发EuroDate.__str__,但是结果为
20 '''
21 输出结果:
22 <__main__.Date object at 0x1013f9d68>
23 '''

因为e就是用父类Date产生的,所以根本不会触发EuroDate.__str__,解决方法就是用classmethod

1 import time
2 class Date:
3     def __init__(self,year,month,day):
4         self.year=year
5         self.month=month
6         self.day=day
7     # @staticmethod
8     # def now():
9     #     t=time.localtime()
10     #     return Date(t.tm_year,t.tm_mon,t.tm_mday)
11
12     @classmethod #改成类方法
13     def now(cls):
14         t=time.localtime()
15         return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪个类来调用,即用哪个类cls来实例化
16
17 class EuroDate(Date):
18     def __str__(self):
19         return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)
20
21 e=EuroDate.now()
22
23 print(e) #我们的意图是想触发EuroDate.__str__,此时e就是由EuroDate产生的,所以会如我们所愿
24 '''
25 输出结果:
26 year:2017 month:3 day:3
27 '''

强调,注意注意注意:静态方法和类方法虽然是给类准备的,但是如果实例去用,也是可以用的,只不过实例去调用的时候容易让人混淆,不知道你要干啥

1 x=e.now() #通过实例e去调用类方法也一样可以使用,静态方法也一样
2 print(x)
3 '''
4 输出结果:
5 year:2017 month:3 day:3
6 '''

 

 

参考资料:

1. http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label10

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐