学习Python中遇到的问题

阅读更多
最近学习Python中。
先上代码:
# -*- 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()

这是我写的一段测试学习代码。报错如下:
Traceback (most recent call last):
  File "", line 1, in 
    import ObjVarTest.py
  File "ObjVarTest.py", line 29, in 
    toby=Person('toby Huang')
TypeError: this constructor takes no arguments

下面是正确的代码:
# -*- 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()

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

你可能感兴趣的:(学习Python中遇到的问题)