引言提到面向对象, 总是离不开几个重要的术语: 多态( Polymorphism ), 继承( Inheritance ) 和封装( Encapsulation )。 Python 也是一种支持 OOP 的动态语言, 本文将简单阐述 Pytho n 对面向对象的支持。在讨论 Python 的 OOP 之前,先看几个 OOP 术语的定义: ?类:对具有相同数据和方法的一组对象的描述或定义。?对象:对象是一个类的实例。?实例(instance) :一个对象的实例化实现。?标识(identity) :每个对象的实例都需要一个可以唯一标识这个实例的标记。?实例属性( instance attribute ):一个对象就是一组属性的集合。?实例方法(instance method) :所有存取或者更新对象某个实例一条或者多条属性的函数的集合。?类属性( classattribute ):属于一个类中所有对象的属性,不会只在某个实例上发生变化?类方法( classmethod ):那些无须特定的对性实例就能够工作的从属于类的函数。 中的类与对象 Python 中定义类的方式比较简单: class 类名: 类变量 def __init__(self,paramers): def 函数(self,...) 其中直接定义在类体中的变量叫类变量, 而在类的方法中定义的变量叫实例变量。类的属性包括成员变量和方法,其中方法的定义和普通函数的定义非常类似,但方法必须以 sel f 作为第一个参数。举例: class MyFirstTestClass: classSpec="it isa test class" def __init__(self,word): print "say "+word def hello(self,name): print "hello "+name 在 Python 类中定义的方法通常有三种: 实例方法, 类方法以及静态方法。这三者之间的区别是实例方法一般都以 self 作为第一个参数, 必须和具体的对象实例进行绑定才能访问, 而类方法以 cls 作为第一个参数, cls 表示类本身, 定义时使用***@classmethod ; 而静态方法不需要默认的任何参数, 跟一般的普通函数类似. 定义的时候使用***@staticmethod 。 class MethodTest(): count= 0 def addCount(self): +=1 print "I am an instance method,my count is" + str(), self ***@staticmethod defstaticMethodAdd(): +=1 print"I ama static methond,my count is"+str() ***@classmethod defclassMethodAdd(cls): +=1 print"I ama class method,my count is"+str(),cls a=MethodTest() () ''' I am an instance method,my count is1 < instanceat 0x011EC990> ''' () ;#I ama static methond,my count is2 () ;#I ama static methond,my count is3 () ;#I ama class method,my count is4 () ;#I ama class method,my count is5 () ''' Traceback(most recent call last): File"<pyshell#5>", line 1, in <module> () TypeError:unbound method addCount() must be called with MethodTest instance asfirst argument (got nothing instead
python 面向对象学习总结介绍 来自淘豆网m.daumloan.com转载请标明出处.