我正在尝试为宠物创建一个类,为从类“Pet”继承名称和品种等的所有者创建另一个类。如何使用类中对象Pet1中的pets名称作为所有者
class Pet: #creates a new class pet
name = ""
breed =""
species="" #initialise the class
age = 0
def petInfo(self): # creates a function petInfo to return the values assigned to the object
Info = ("Your pets name is: %s Your pets breed is: %s Your pets species is: %s and It's age is: %s" % (self.name, self.breed, self.species, self.age))
return Info
Pet1 = Pet() #creates a new object Pet1 from the class Pet
Pet1.petInfo() #accesses the function in the class
PetsName = input("What is their name? ")
PetsBreed = input("What is it's breed? ")
PetsSpecies = input("What is it's species? ") #Ask for input for the new
values
PetsAge = int(input("What is it's age?"))
Pet1.name = PetsName
Pet1.breed = PetsBreed
Pet1.species = PetsSpecies #assigns the inputed values to the object
Pet1.age = PetsAge
print(Pet1.petInfo()) #prints the "Info" variable inside the function "petInfo"
################################ Inheritance
#########################################
class owner(Pet):
ownerName = ""
ownerPostcode = ""
ownerPhonenumber = ""
def ownerInfo(self):
OwnerInformation = ("Owners name is: %s and their pets name is: %s"
% (self.ownerName, self.name))
return OwnerInformation
Owner1 = owner()
Owner1.ownerInfo()
NewName = input("What is your name?: ")
Owner1.ownerName = NewName
print(Owner1.ownerInfo())
你应该更喜欢组合而不是继承。主人不是宠物,主人有宠物。我建议采取以下办法:
或者宠物有主人:
相关问题 更多 >
编程相关推荐