问题
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