Python学习笔记之面向对象

来源:互联网 发布:js调用webservice接口 编辑:程序博客网 时间:2024/04/30 08:50

转自:http://www.cnblogs.com/known/archive/2010/09/04/1818231.html

前面提到的操作函数和语句块是传统的面向过程编程,而编写大型程序,通常采用面向对象编程。类和对象是面向对象编程的两个主要方面,类创建一个新类型,而对象是类的实例。Python没有什么值类型与引用类型之分,它把所有事物统统看作是类。类使用class关键字来创建。

1. Self

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。

你一定很奇怪Python如何给self赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。

2. 类

一个空类:

view sourceprint?
1class Person:
2    pass #An empty block

类的使用:

view sourceprint?
1p = Person()
2print(p)

3. 方法

类/对象可以拥有像函数一样的方法,这些方法与函数的区别只是一个额外的self变量。

view sourceprint?
1class Person:
2    def sayHi(self):
3        print("Hello, how are you?")
4  
5p = Person()
6p.sayHi()

注意调用sayHi方法时没有任何参数,但仍然在函数定义时有self。

4. __init__方法

在Python的类中有很多方法的名字有特殊的重要意义。像__init__,类似于构造函数。__init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的初始化 。注意,这个名称的开始和结尾都是双下划线。

view sourceprint?
01class Person:
02    def __init__(self, name):
03        self.name = name
04  
05    def sayHi(self):
06        print("Hello, my name is", self.name)
07  
08  
09p = Person("known")
10p.syaHi()

5. 域

Python有两种类型的域——类的变量对象的变量,它们根据是类还是对象拥有这个变量而区分。
类的变量由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
对象的变量由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。

view sourceprint?
01class Person:
02    '''Represnets a person.'''
03    population = 0
04  
05    def __init__(self, name):
06        '''Initializes the person's data.'''
07        self.name = name
08        print("(Initializing %s)" % self.name)
09  
10        #When this person is created, he/she adds to the population
11        Person.population += 1
12  
13    def __del__(self):
14        '''I am dying.'''
15        print("%s says bye." % self.name)
16  
17        Person.population -= 1
18  
19        if Person.population == 0:
20            print("I am the last one.")
21        else:
22            print("There are still %d people left." % Person.population)
23  
24    def sayHi(self):
25        '''Greeting by the person.
26          Really, that's all it does.'''
27        print("Hi, my name is %s." % self.name)
28  
29    def howMany(self):
30        '''Prints the current population.'''
31        if Person.population == 1:
32            print("I am the only person here.")
33        else:
34            print("We have %d person here." % Person.population)
35  
36  
37swaroop = Person('Swaroop')
38swaroop.sayHi()
39swaroop.howMany()
40  
41kalam = Person('Abdul Kalam')
42kalam.sayHi()
43kalam.howMany()
44  
45swaroop.sayHi()
46swaroop.howMany()
47  
48del kalam
49del swaroop

运行结果:

(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.

6. 继承

在类名后面跟一对圆括号,基类名写在圆括号内。

view sourceprint?
01class SchoolMember:
02    '''Represents any school member.'''
03    def __init__(self, name, age):
04        self.name = name
05        self.age = age
06        print("(Initialized SchoolMember: %s)" % self.name)
07  
08    def tell(self):
09        '''Tell my details.'''
10        print("Name:'%s' Age:'%s'" % (self.name, self.age))
11  
12class Teacher(SchoolMember):
13    '''Represents a teacher.'''
14    def __init__(self, name, age, salary):
15        SchoolMember.__init__(self, name, age)
16        self.salary = salary
17        print("(Initialized Teacher: %s)" % self.name)
18  
19    def tell(self):
20        SchoolMember.tell(self)
21        print("Salary: '%d'" % self.salary)
22  
23class Student(SchoolMember):
24    '''Represents a student.'''
25    def __init__(self, name, age, marks):
26        SchoolMember.__init__(self, name, age)
27        self.marks = marks
28        print("(Initialized Student: %s)" % self.name)
29  
30    def tell(self):
31        SchoolMember.tell(self)
32        print("Marks: '%d'" % self.marks)
33  
34  
35t = Teacher("Mrs. Shrividya", 40, 30000)
36s = Student("Swaroop", 22, 75)
37  
38print() # prints a blank line
39  
40members = [t, s]
41for member in members:
42    member.tell() # works for both Teachers and Students

输出结果:

(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)


Name:'Mrs. Shrividya' Age:'40' Salary: '30000'
Name:'Swaroop' Age:'22' Marks: '75'

原创粉丝点击