面向对象的编程 到目前为止,在我们的程序中,我们都是根据操作数据的函数或语句块来设计程序的。这被称为 面向过程的 编程。还有一种把数据和功能结合起来,用称为对象的东西包裹起来组织程序的方法。这种方法称为 面向对象的 编程理念。 类和对象是面向对象编程的两个主要方面。类创建一个新类型,而对象这个类的 实例 。这类似于你有一个 属于一个对象或类的变量被称为域。对象也可以使用 属于 类的函数来具有功能。这样的函数被称为类的方法。这些术语帮助我们把它们与孤立的函数和变量区分开来。域和方法可以合称为类的属性。 self Python中的self等价于C++中的self指针和Java、C#中的this参考。 类 使用 >>> class person: pass >>> p=person() 使用类名后跟一对圆括号来创建一个对象/实例 >>> print p 简单地打印了这个变量的类型 <__main__.person instance at 0x00BA1F08> 它告诉我们我们已经在 方法 类/对象可以拥有像函数一样的方法,这些方法与函数的区别只是一个额外的 >>> class person: def say(self): print 'hello world' >>> p=person() >>> p.say() hello world __init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。 __init__方法类似于C++、C#和Java中的 constructor 。 >>> class person: def __init__(self,name): self.name=name def say(self): print 'my name is',self.name >>> p=person('michael') >>> p.say() my name is michael 有两种类型的 域 ——类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分。 类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。 对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。 >>> class person: population=0 类的变量 def __init__(self,name): self.name=name 对象的变量(使用self赋值) person.population+=1 类的变量(使用类名赋值) print 'my name is',self.name def many(self): if person.population==0: print 'there have no people' elif person.population==1: print 'there are only one people' else: print 'there are %d people here'%person.population >>> p=person('michael') my name is michael >>> p.many() there are only one people >>> p=person('hack') my name is hack >>> p.many() there are 2 people here 继承 面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过 继承 机制。 为了使用继承,我们把基本类的名称作为一个元组跟在定义类时的类名称之后,如果在继承元组中列了一个以上的类,那么它就被称作 多重继承 Python不会自动调用基本类的constructor,你得亲自专门调用它。 >>> class baseclass: def __init__(self,name,age): self.name=name self.age=age def say(self): print 'name',self.name,'age',self.age >>> class sonclass(baseclass): 基本类是在类定义的时候,在元组之中指明的 def __init__(self,name,age,salary): baseclass.__init__(self,name,age) Python不会自动调用基本类的constructor,你得亲自专门调用它 self.salary=salary def say(self): baseclass.say(self) print 'salary',self.salary >>> son=sonclass('michael',23,1000) >>> son.say() Python总是首先查找对应类型的方法,如果它不能在子类中找到对应的方法,它才开始到基本类中逐个查找 name michael age 23 salary 1000 |
|