我在自学python类,当我运行我的代码时,我得到了以下错误:
    class Critter(object):
        """A virtual pet"""
            def _init_(self, name, mood):
                print("A new critter has been born!!!!!")
                self.name = name
                self.__mood = mood 
           def talk(self):
           print("\n Im",self.name)
           print("Right now I feel",self._mood)
           def _private_method(self):
               print("this is a private method")
           def public(self):
               print("This is a public method. ")
               self._private_method( )
crit = Critter(name = "Poochie", mood = "happy")
crit.talk( )crit.public_method( )
input("Press enter to leave")我收到以下错误:
    Traceback (most recent call last):
File "/Users/calebmatthias/Document/workspace/de.vogella.python.first/practice.py", line   27, in <module>
    crit = Critter(name = "Poochie", mood = "happy")
TypeError: object.__new__() takes no parameters发布于 2011-12-01 11:05:12
我建议您更仔细地格式化您的提交。Python在缩进方面非常挑剔--请阅读PEP8以获得有关如何正确格式化Python代码的良好介绍。
问题是你把__init__拼错了。你有_init_,它只是Python的另一种方法。
发布于 2011-12-01 12:40:59
请注意,以下更正的代码运行正常(_init_更改为__init__;_mood更改为__mood;public_method更改为public;缩进已更正):
class Critter(object):
    """A virtual pet"""
    def __init__(self, name, mood):
        print("A new critter has been born!!!!!")
        self.name = name
        self.__mood = mood 
    def talk(self):
        print("\n Im",self.name)
        print("Right now I feel",self.__mood)
    def _private_method(self):
        print("this is a private method")
    def public(self):
        print("This is a public method. ")
        self._private_method( )
crit = Critter(name="Poochie", mood="happy")
crit.talk()
crit.public()
input("Press enter to leave")对输出执行...and操作:
A new critter has been born!!!!!
 Im Poochie
Right now I feel happy
This is a public method. 
this is a private method
Press enter to leavehttps://stackoverflow.com/questions/8336234
复制相似问题