python如何创建一个类_在Python中创建一个Dog类

这是我第一次使用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

啊那些小细节。谢谢你们的帮助! –

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值