我是 Python 的新手,我目前使用 Python 3x,但我总是收到此错误,有人可以帮助我吗?


class Dog():
snip
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")

错误:

Traceback (most recent call last): 
File "dog", line 1, in <module> class Dog(): snip File "dog", line 1, in Dog class Dog(): snip 
NameError: name 'snip' is not defined

你缺少构造函数,

在这里,您应该定义要传递的参数是什么

class Dog:
def __init__(self,name,age):
self.name = name
self.age  = age
# this way you are telling the class what is the argument you are passing
# and how to assign it as class property

my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name+ ".")
print("My dog is " + str(my_dog.age) + " years old.")

最新更新