这是我第一次使用python编程,我目前正在研究如何创建一个类。下面是我的代码:在Python中创建一个Dog类
class Dog():#Defining the class
"""A simple attempt to model a dog."""#Doc string describing the class
def _init_(self, name, age):#Special method that Python runs automatically when a new instance is created.
#Self must be the first variable in this function
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
my_dog = dog('willie', 6)#Telling python to create the dog named willie who is 6.
print("My dog's name is " + my_dog.name.title() + ".")#Accessing the value of the variable created
print("My dog is " + str(my_dog.age) + " years old.")#Accessing the value of the 2nd variable
不过,我得到试图建立,指出时的错误消息:
Traceback (most recent call last):
File "dog.py", line 19, in
my_dog = dog('willie', 6)#Telling python to create the dog named willie who is 6.
NameError: name 'dog' is not defined
任何想法?构造一个实例时
class Dog:
'A simple dog model.'
def __init__(self, name, age):
'Construct name and age attributes for an instance of Dog'
self.name = name.title()
self.age = age
def sit(self):
'Simulate a dog sitting in response to a command.'
print(self.name + " is now sitting.")
def roll_over(self):
'Simulate rolling over in response to a command.'
print(self.name + " rolled over!")
my_dog = Dog(name='willie', age=6)
print("My dog's name is " + my_dog.name + ".")
print("My dog is " + str(my_dog.age) + " years old.")
标题情况下,一次名:
2017-02-22
D.Wes
+4
'狗'不是'狗'! –
+4
另外'_init_'不是'__init__'。 –
+0
啊那些小细节。谢谢你们的帮助! –