学习Python中遇到的问题

最近学习Python中。
[size=large][b]先上代码:[/b][/size]

# -*- coding: UTF-8 -*-
class Person:
'''Represents a person'''
population=0
def _init_(self,name):
self.name=name
print '初始化参数 %s'%self.name
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 leftl'%Person.population
def sayHi(self):
'''Greeting by the people.

Really,that's all it does.'''
print 'Hi,My name is %s'%self.name
def howMany(self):
'''print the current population'''
if Person.population==1:
print 'I am the only one person here'
else:
print 'We have %d persons here'%Person.population
print '测试开始!'
toby=Person('toby Huang')
toby.sayHi()
toby.howMany()

jimmy=Person('jimmy Huang')
jimmy.sayHi()
jimmy.howMany()

toby.sayHi()
toby.howMany()

[size=large][b]这是我写的一段测试学习代码。报错如下:[/b][/size]

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
import ObjVarTest.py
File "ObjVarTest.py", line 29, in <module>
toby=Person('toby Huang')
TypeError: this constructor takes no arguments

[size=large][b]下面是正确的代码:[/b][/size]

# -*- coding: UTF-8 -*-
class Person:
'''Represents a person'''
population=0
def __init__(self,name):
self.name=name
print '初始化参数 %s'%self.name
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 leftl'%Person.population
def sayHi(self):
'''Greeting by the people.

Really,that's all it does.'''
print 'Hi,My name is %s'%self.name
def howMany(self):
'''print the current population'''
if Person.population==1:
print 'I am the only one person here'
else:
print 'We have %d persons here'%Person.population
print '测试开始!'
toby=Person('toby Huang')
toby.sayHi()
toby.howMany()

jimmy=Person('jimmy Huang')
jimmy.sayHi()
jimmy.howMany()

toby.sayHi()
toby.howMany()

[b]是不是一眼没看出有什么不一样?
开始的时候我也是快读浏览了下,然后就直接开始写了。知道运行时报错,都一直找不到错在哪?直到写这篇博客前,才发现错误!
其实这真是一个低级错误,原来不是_inti_方法,应该是__init__方法!我少打了一个_。
这都是快速浏览带来的恶果啊,就因为这简单错误害我两天都不爽。
还是那句话:Devil in the details
[/b]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值