我正在自学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
答案 0 :(得分:4)
我建议您更仔细地格式化提交内容。 Python非常挑剔缩进 - 请阅读PEP8,了解如何正确格式化Python代码。
问题是您拼错__init__
错误。你有_init_
这只是Python的另一种方法。
答案 1 :(得分:0)
请注意,以下更正的代码运行正常(_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")
...和输出:
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