python --面向对象的语言,其最大的特性 为 封装,继承,多态。
封装:封装可以不关心对象是如何构建的而直接进行使用。是对全局作用域中其他区域隐藏多余信息的原则
定义类:
1 >>> class Person(): 2 def setName(self,name): 3 self.name = name 4 def getName(self): 5 return self.name 6 def greet(self): 7 print ‘hello i am %s‘ % self.name
self : 是对对象自身的引用,是 方法(更专业点的可称为 绑定方法) 和 函数的区别
1 >>> foo = Person() 2 >>> bar = Person() 3 >>> foo.setName(‘zhang‘) 4 >>> bar.setName(‘di‘) 5 >>> foo.greet() 6 hello i am zhang 7 >>> bar.greet() 8 hello i am di
特性可以在外部访问
1 >>> foo.name 2 ‘zhang‘ 3 >>> bar.name 4 ‘di‘ 5 >>> bar.name = ‘lu‘ 6 >>> bar.greet() 7 hello i am lu
私有方法,类外部不可调用,内部可调用,用 "__"开头即可
1 class Service: 2 def __a(self): 3 print "you can‘t see me" 4 5 def b(self): 6 print "you can see me" 7 self.__a() 8 9 >>> s = Service() 10 >>> s.__a() 11 12 Traceback (most recent call last): 13 File "<pyshell#29>", line 1, in <module> 14 s.__a() 15 AttributeError: Service instance has no attribute ‘__a‘ 16 >>> s.b() 17 you can see me 18 you can‘t see me
类的定义其实就是执行代码块
1 >>> class a: 2 print "a is created" 3 4 5 a is created
注意下面代码的区别
1 >>> class MemberCount(): 2 members = 0 3 def init(self): 4 self.members += 1 5 7 >>> m1 = MemberCount() 8 >>> m1.init() 9 >>> m1.members 10 1 11 >>> m2 = MemberCount() 12 >>> m2.init() 13 >>> m2.members 14 1 15 >>> class MemberCount(): 16 members = 0 17 def init(self): 18 MemberCount.members += 1 19 21 >>> m1 = MemberCount() 22 >>> m1.init() 23 >>> m1.members 24 1 25 >>> m2 = MemberCount() 26 >>> m2.init() 27 >>> m2.members 28 2 29 >>> m1.members 30 2
指定超类
1 >>> class Filter: 2 def init(self): 3 self.blocked = [] 4 def filter(self,sequence): 5 return [x for x in sequence if x not in self.blocked] 6 7 8 >>> class SapmFilter(Filter): 9 def init(self): 10 self.blocked = [‘SPAM‘] 11 12 13 >>> s = SapmFilter() 14 >>> s.init() 15 >>> s.filter([‘SPAM‘,‘EFF‘,‘A‘,‘SPAM‘])
调查继承 想要查看一个类是否是另一个类的子类 ,可以用 内置的 issubclass 函数
1 >>> issubclass(SapmFilter,Filter) 2 True 3 >>> issubclass(Filter,SapmFilter) 4 False 5 #查看已知类的父类 6 >>> SapmFilter.__bases__ 7 (<class __main__.Filter at 0x0299B0D8>,) 8 >>> s = SapmFilter() 9 #查看 对象是否是类的实例 10 >>> isinstance(s,SapmFilter) 11 True 12 >>> isinstance(s,Filter) 13 True 14 >>> isinstance(s,str) 15 False
多个超类 多重继承 尽量少用,且如果一个方法如果从多个超类继承(也就是两个超类具有相同名字的不同方法),先继承类中的方法会重写后继承类中的方法
1 >>> class A: 2 def aa(self): 3 print "this is a" 4 5 6 >>> class B: 7 def bb(self): 8 print "this is b" 9 10 11 >>> class c(A,B): 12 pass 13 14 >>> cc = c() 15 16 17 >>> cc.aa() 18 this is a 19 >>> cc.bb() 20 this is b 21 22 >>> c.__bases__ 23 (<class __main__.A at 0x0299B148>, <class __main__.B at 0x0299B1B8>)
时间: 2024-10-06 12:04:57