Python面向对象的编程

在Python中,即便是整数也被作为对象 (属于int类)。这和C++把整数作为类型是不同的 。通过help(int) 可以了解更多这个int类的信息。

[注意]
[1] 使用类名后跟一对圆括号 来创建一个对象/实例。
[2] Python中的self 等价于C++中的this指针
[3] __init__方法 类似于C++中的constructor
[4] __del__方法 类似于C++中的destructor
[5] 是属于一个对象或类的变量。域有两种类型 :实例变量(对象的变量 )和类变量(类的变量
[6] 方法 是属于类的函数。
[7] 域和方法统称属性
[8] __del__方法在对象消逝的时候调用,并把对象所占的内存返回给系统。
[9] Python中所有的类成员都是公共的
[10] __privatevar的双下划线前缀 命名方式为私有变量 。但是,惯例是:使用单下划线前缀 表示私有变量。

#! /usr/bin/python # Filename: objvar.py # 2010-7-13 wcdj class Person: '''Represents a person.''' population=0 def __init__(self,name): '''Initializes the person's data.''' self.name=name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying''' 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): '''Greeting by the person Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population.''' if Person.population==1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population print '-------------------' print 'Person: ',Person.__doc__ print 'Person.__init__:',Person.__init__.__doc__ print 'Person.__del__:',Person.__del__.__doc__ print 'Person.sayHi:',Person.sayHi.__doc__ print 'Person.howMany:',Person.howMany.__doc__ print '-------------------' def main(): gerry=Person('Gerry Young') gerry.sayHi() gerry.howMany() w=Person('wcdj') w.sayHi() w.howMany() if __name__ == '__main__': main() ######### # output ######### >>> ------------------- Person: Represents a person. Person.__init__: Initializes the person's data. Person.__del__: I am dying Person.sayHi: Greeting by the person Really, that's all it does. Person.howMany: Prints the current population. ------------------- (Initializing Gerry Young) Hi, my name is Gerry Young. I am the only person here. (Initializing wcdj) Hi, my name is wcdj. We have 2 persons here. Gerry Young says bye. there are still 1 people left. wcdj says bye. I am the last one. >>>

 

关于上述代码的问题讨论可见:

[1] http://topic.csdn.net/u/20100714/14/5e94e0c6-b958-4469-b116-76857f72ae15.html?seed=252010780&r=67002597#r_67002597

[2] http://topic.csdn.net/u/20100617/00/55e2d94b-1dc7-40ee-ad15-18cef7fba89b.html


你可能感兴趣的:(编程,c,python,Constructor,2010,destructor)