byteofpython中的例子:
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the persons 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):
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
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
|
1. __init__():类似于构造函数,在实例生成的时候初始化 例子中在对象生成时把参数name传进来
__del__():应该就类似于析构函数了吧 如果不显示调用 则在程序退出时调用
2. 关于self:传说中类似于C++中的this 但我不记得this的细节了>< self就是自己吧 byteofpython中是这样解释的:
你一定很奇怪Python如何给self
赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。假如你有一个类称为MyClass
和这个类的一个实例MyObject
。当你调用这个对象的方法MyObject.method(arg1, arg2)
的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)
——这就是self
的原理了。
3. 由程序的结果来看 类的变量population是所有的实例所共用的!! 第几次Person就是几!
4. print语句中的%:由于print != printf 所以想要像printf那样按照格式打印就要用% 一个参数可以像上例那样表示 当多于一个参数时 要用元组(或字典 ?)表示每个参数的键值
为什么用到population的时候一定要Person.population ? 否则出错 !
否则是方法里的私有属性?重定义?
PS. 运行结果:
(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.
tags: VIM python cscope
首先cd到目标目录,然后
find . -name '*.py' > cscope.files
然后
cscope -b
最后在vim里目标目录下
cs a cscope.out
Happy!
阅读(1119) | 评论(1) | 转发(0) |