用Python创建Dog类

时间:2017-02-22 03:22:39

标签: python-3.x

这是我第一次使用python编程,我目前正在研究如何创建一个类。以下是我的代码:

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 <module>
    my_dog = dog('willie', 6)#Telling python to create the dog named willie who is 6.
NameError: name 'dog' is not defined

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

这是一个改进的版本:

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

在构造实例时标题名称一次。这是“不要重复自己”的一个例子,也就是DRY原则。

答案 1 :(得分:0)

class Dog():
    """一次模拟小狗的简单尝试"""

    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        """模拟小狗被命令时坐下"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title() + " rolled over!")

my_dog = Dog('White', 6)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")

也许您使用缩进将my_dog错误地插入了Class Dog()

答案 2 :(得分:-1)

您有两个问题:

my_dog = Dog(name='willie', age=6) ## make sure the class name is capital
dog == Dog(******)

此外,您的__init__需要两个下划线:
__init__是正确的,
_init_不正确。

尝试这些修改!