麻烦来了,随着继续看Byte-of-python 发现会遇到一些莫名其妙的问题:
class Robot:
'''Represents a robot, with a name.'''
population = 0
def __init__(self,name):
'''Initializes the data.'''
self.name = name
print('(Initializing{0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot
Yeah, they can do that.'''
print('Greetings, my masters call me {0}'.format(self.name))
def howMany(klass):
'''Prints the current population.'''
print('We have {0:d} robots'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3P0')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destory them.")
del droid1
del droid2
Robot.howMany() [code snippet: http://snipt.org/Pll ]
上面这段代码运行结果是:
Traceback (most recent call last):
File “F:\PJ\PythonPJ\objvar.py”, line 1, in <module>
class Robot:
File “F:\PJ\PythonPJ\objvar.py”, line 34, in Robot
droid1 = Robot(‘R2-D2′)
NameError: name ‘Robot’ is not defined
奇怪,只好再检查一次代码中有没有一些低级错误…暂时还没有什么发现…问题是拷贝PDF中提到的代码也是同样的错误…为什么Robot会没有define…
似乎是缩进的问题,调整了缩进之后的代码:
class Robot:
'''Represents a robot, with a name.'''
population = 0
def __init__(self,name):
'''Initializes the data.'''
self.name = name
print('(Initializing{0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot
Yeah, they can do that.'''
print('Greetings, my masters call me {0}'.format(self.name))
def howMany(klass):
'''Prints the current population.'''
print('We have {0:d} robots'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3P0')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destory them.")
del droid1
del droid2
Robot.howMany() [code snippet: http://snipt.org/Plm ]
这下可以initialize Robot了。可是问题又来,
(InitializingR2-D2)
Greetings, my masters call me R2-D2
Traceback (most recent call last):
File “F:\PJ\PythonPJ\objvar.py”, line 36, in <module>
Robot.howMany()
TypeError: howMany() takes exactly 1 positional argument (0 given)
**Note:本文中用Snipt.org输出的代码,在RSS阅读器中没法输出…