gpt4 book ai didi

python - 宠物类 python

转载 作者:行者123 更新时间:2023-11-30 23:19:31 27 4
gpt4 key购买 nike

此作业的说明:编写一个名为 Pet 的类,该类应具有以下属性:

  • __姓名
  • __animal_type
  • __年龄

它将具有以下方法:

  • 设置名称
  • 设置动物类型
  • 设定年龄
  • 获取名称
  • 获取动物类型
  • 获取年龄

编写完此类后,编写一个程序来创建该类的对象并提示用户输入宠物的名称、类型和年龄。数据应存储为对象的属性。使用对象的访问器方法检索宠物的名称、类型和年龄并显示在屏幕上。

这是我的代码:

class Pet(object):
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age

def set_name(self, name):
self.__name = name

def set_type(self, animal_type):
self.__animal_type = animal_type

def set_age(self, age):
self.__age = age

def get_name(self):
return self.__name

def get_animal_type(self):
return self.__animal_type

def get_age(self):
return self.__age


# The main function
def main():
# Create an object from the Pet class
pets = Pet(name, animal_type, age)

# Prompt user to enter name, type, and age of pet
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
print('This will be added to the records. ')
print('Here is the data you entered:')
print('Pet Name: ', pets.get_name)
print('Animal Type: ', pets.get_animal_type)
print('Age: ', pets.get_age)

main()

当我运行该程序时,出现以下错误:UnboundLocalError:赋值前引用的局部变量“名称”

最佳答案

在 main() 函数中,Pet() 类对象需要参数。因此,您首先需要提供参数,然后将它们输入到 Pet() 类对象中。

class Pet:
def __init__(self, name,animal_type,age):
self.__name = name
self.__animal_type = animal_type
self.__age = age

def set_name(self,name):
self.__name = name

def set_animal_type(self,animal_type):
self.__animal_type = animal_type

def set_age(self,age):
self.__age = age

def get_name(self):
return self.__name

def get_age(self):
return self.__age

def get_animal_tpe(self):
return self.__animal_type


def main():
pet_name = input('Please enter your pet\'\s name: ')
pet_type = input('What animal is your pet?')
pet_age = float(input('What is the age of your pet?'))

pet_specs = Pet(pet_name,pet_type,pet_age)

print('pet name is ', pet_specs.get_name())
print('pet type is ', pet_specs.get_animal_tpe())
print('pet age is ', pet_specs.get_age())

main()

关于python - 宠物类 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26031637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com