类和对象是面向对象编程的两个方面。

类的方法和普通函数只有一个区别,他们必须有一个额外的参数,在调用这个方法时不需要为这个参数赋值,python为自动为其赋值,这个变量就是self

举个例子

有一个类叫做MyClass,一个类对象叫做MyObject

调用myclass的方法method

MyObject.method(arg1, arg2)

python会自动转换成

MyClass.method(MyObject, arg1, arg2)

#!/usr/bin/python#filename:  simpleclass.pyclass Person:#this is an empty block      passp = Person()print p
$ python simpleclass.py <__main__.Person instance at 0x7f810657eef0>

这里就在Person类中定义的方法sayHi增加了一个self参数

#!/usr/bin/python#filename: method.pyclass Person:   def sayHi(self):       print 'Hello,how are you?'p = Person()p.sayHi()#also can be written like thisPerson().sayHi()
$ python method.py Hello,how are you?Hello,how are you?

__init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意,这个名称的开始和结尾都是双下划线。

#!/usr/bin/pythonclass Person:   def __init__(self,name):       self.name = name   def sayHi(self):       print 'Hello, my name is',self.namep = Person('John')p.sayHi()#this also can be written like this Person('John').sayHi()
$ python class_init.py Hello, my name is JohnHello, my name is John

类变量和对象变量

#!/usr/bin/python# filename: objvar.pyclass Person:    population = 0    def __init__(self,name):        self.name = name        print '(Initializing %s)' % self.name        Person.population += 1    def __del__(self):        print '%s says bye.'  % self.name        Person.population -= 1        if Person.population == 0:           print 'I am the last one.'        else:           print 'There are still %d people left.' %Person.population    def sayHi(self):        print 'Hi, my name is %s.' % self.name    def howMany(self):        if Person.population == 1:           print 'I am the only person here.'        else:           print 'We have %s people here'  % Person.populationswaroop = Person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam = Person('Abdul Kalam')kalam.sayHi()kalam.howMany()swaroop.sayHi()swaroop.howMany()

$ python objvar.py (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 people hereHi, my name is Swaroop.We have 2 people hereAbdul Kalam says bye.There are still 1 people left.Swaroop says bye.I am the last one.

观察可以发现__init__方法用一个名字来初始化Person实例。在这个方法中,我们让population增加1,这是因为我们增加了一个人。同样可以发现,self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。

记住,你能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。

在这个程序中,我们还看到docstring对于类和方法同样有用。我们可以在运行时使用Person.__doc__Person.sayHi.__doc__来分别访问类与方法的文档字符串。

就如同__init__方法一样,还有一个特殊的方法__del__,它在对象消逝的时候被调用。对象消逝即对象不再被使用,它所占用的内存将返回给系统作它用。在这个方法里面,我们只是简单地把Person.population1

当对象不再被使用时,__del__方法运行,但是很难保证这个方法究竟在 什么时候 运行。如果你想要指明它的运行,你就得使用del语句,就如同我们在以前的例子中使用的那样。

继承就是为了实现代码的重用

#!/usr/bin/python#filename: inherit.pyclass SchoolMember:    def __init__(self,name,age):        self.name = name        self.age = age        print '(Initialized SchoolMember: %s)'  % self.name    def tell(self):        print 'Name:"%s" Age:"%s"' % (self.name,self.age),class Teacher(SchoolMember):    def __init__(self,name,age,salary):        SchoolMember.__init__(self,name,age)        self.salary = salary        print '(Initialized Teacher: %s)' % self.name    def tell(self):        SchoolMember.tell(self)        print 'Salary: "%d"' % self.salaryclass Student(SchoolMember):    def __init__(self,name,age,marks):        SchoolMember.__init__(self,name,age)        self.marks = marks        print '(Initialized Student: %s)' % self.name    def tell(self):        SchoolMember.tell(self)        print 'Marks: "%d" ' %self.markst = Teacher('Mrs. Shrividya',40,30000)s = Student('Swaroop', 22, 75)printmembers = [t, s]for member in members:    member.tell()

$ python inherit.py (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"

参考文档: