I keep on getting a type error

一个人想着一个人 提交于 2019-12-31 05:46:05

问题


Well I'm teaching myself about python classes and when I run my code I get the following error:

    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")

I receive the error:

    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

回答1:


I would recommend that you more carefully format your submissions. Python is really picky about indentation -- read PEP8 for a good intro on how to properly format Python code.

The problem is that you spelled __init__ wrong. You have _init_ which is just another method to Python.




回答2:


Note that the following corrected code runs fine (_init_ changed to __init__; _mood changed to __mood; public_method changed to public; indentation corrected):

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 the output:

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 leave


来源:https://stackoverflow.com/questions/8336234/i-keep-on-getting-a-type-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!