Python学习笔记:05类

Python是面向对象的语言,面向对象最重要的三个优点有:

  • 多态:多态使对象具备不同的行为方式。(可以认为声明了接口,但是实现方式可能多样)
  • 封装:封装是对全局作用域中隐藏多余信息的原则(创建对象,隐藏属性,不用担心对全局产生影响,也不用担心全局影响对象属性)
  • 继承:继承使得代码可以复用,而且使得类之间有超类和子类的概念

创建类

类的可见级别在类中分别定义了一个公共的方法greet,保护方法_protectmethod,私有方法__privatemethod。如同通过Tab键进行函数定义控制,通过下划线_可以表明方法的可见级别。

__metaclass__= type
class Person:
    def setName(self,name):
        self.name=name
    def getName(self,name):
        return self.name
    def greet(self):
        print "hello, world! I'm %s." % self.name
    def _protectmethod(self):
        print '_protectmethod'
    def __privatemethod(self):
        print '__privatemethod'
foo=Person()
foo.setName('foo')
foo.greet()
hello, world! I'm foo.
foo.name
'foo'
func=foo.greet
func()
hello, world! I'm foo.
foo.setName('notfoo')
func()
hello, world! I'm notfoo.

使用单下划线定义的方法不会被带星号的import语句导入(from module import *)

foo._protectmethod()
_protectmethod

使用双下划线定义的方法,外部无法访问,实际上是方法名发生了变化

foo.__privatemethod()
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-17-3353363f5043> in <module>()
----> 1 foo.__privatemethod()


AttributeError: 'Person' object has no attribute '__privatemethod'

在知道方法名改变的规则之后,我们依然可以调用私有方法。

foo._Person__privatemethod()
__privatemethod

类属性

class MemberCounter:
    memNum=0
    def init(self):
        MemberCounter.memNum+=1
m1=MemberCounter()
m1.init()
m2=MemberCounter()
m2.init()
print MemberCounter.memNum
2
m1.myname='M1'
print m1.myname
M1

类的继承

class Men(Person):
    def greet(self):
        print "hello, world I'm Mr %s" % self.name

m=Men()
m.setName('Andrew')
m.greet()
hello, world I'm Mr Andrew

多个超类

class Singer():
    def sing(self):
        print 'singing'
class MenSinger(Men,Singer):
    def greetandsing(self):
        self.greet()
        self.sing()
ms=MenSinger()
ms.setName('Adrew')
ms.greetandsing()
hello, world I'm Mr Adrew
singing

接口和内省

hasattr(ms,'greet')
True
hasattr(ms,'bark')
False
posted @ 2016-07-17 08:53  sunqiang  阅读(214)  评论(0编辑  收藏  举报