python中什么叫类?
可以视为种类或者类型的同义词。所有的对象都属于某一个类,称为类的实例。
例如:鸟就是"鸟类"的实例。这就是一个有很多子类的一般(抽象)类:看到的鸟可能属于子类"百灵鸟"。可以将"鸟类"想象成所有鸟的集合,而"百灵鸟类"是其中的一个子集。当一个对象所属的类是另外一个对象所属类的子集时,前者就被称为后者的子类,所以"百灵鸟类"是"鸟类"的子类,"鸟类"是"百灵鸟类"的超类
定义子类只是个定义更多方法的过程.
创建类
>>> class Person: def setName(self,name): self.name=name def getName(self): return self.name def greet(self): print "Hello,world! I'm %s" % self.name >>> foo=Person()>>> bar=Person()>>> foo.setName('Nsds')>>> bar.setName('Ysdy')>>> foo.greet()Hello,world! I'm Nsds>>> bar.greet()Hello,world! I'm Ysdy
在调用foo的setName和greet函数时,foo自动将自己作为第一个参数传入函数中,因此命名为self。没有self的话,成员方法就没法访问他们要对其特性进行操作的对象本身了
特性是可以外部访问的:
>>> foo.name'Nsds'>>> bar.name='Yoda'>>> bar.greet()Hello,world! I'm Yoda
特性、函数、方法
self参数事实上正是方法和函数的区别。方法将它们的第一个参数绑定到所属的实例上,因此这个参数可以不必提供。所以可以将特性绑定到一个普通函数上,这样就不会有特殊的self参数了:
(特性是对象内部的变量,对象的状态由它的特性来描述,对象的方法可以改变它的特性,可以直接从对象外部访问特性)
>>> class Class: def method(self): print 'I have a self!' >>> def function(): print "I don't...">>> s=Class()>>> s.method()I have a self!>>> s.method=function>>> s.method()I don't...
变量birdsong引用绑定方法bird.sing上,还是对self参数的访问(仍旧绑定到类的相同实例上)
>>> class Bird: song='Squaawk' def sing(self): print self.song >>> bird=Bird()>>> bird.sing()Squaawk>>> birdsong=bird.sing>>> birdsong()Squaawk
在名称前加上双下划线,可以让方法或者特性变为私有(从外部无法访问)
>>> class Secretive: def __inaccessible(self): print "Bet you can't see me..." def accessible(self): print "The secret message is:" self.__inaccessible() <div style="color:transparent">本文来源gaodai.ma#com搞##代!^码网(</div> >>> s=Secretive()>>> s.__inacessible()Traceback (most recent call last): File "<pyshell#182>", line 1, in <module> s.__inacessible()AttributeError: 'Secretive' object has no attribute '__inacessible'>>> s.accessible()The secret message is:Bet you can't see me...
在类的内部定义中,所有以双下划线开的名字都被"翻译"成前面加上单下划线和类名的形式
>>> Secretive._Secretive__inaccessible<unbound method Secretive.__inaccessible>>>> s._Secretive__inaccessible()Bet you can't see me...