0
これは私の最初のPythonプログラミングの経験であり、現在はクラスの作成方法について作業中です。以下は、私のコードは次のとおりです。ただし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
任意のアイデア?インスタンスを作成するときに名前一度
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.")
タイトルケース:
「dog」は「Dog」ではありません! –
また、 '_init_'は' __init__'ではありません。 – user2357112
ああ、それらの小さな詳細。助けてくれてありがとう! –