如何将属性从对象Pet1继承到新的类所有者?

2024-09-27 00:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为宠物创建一个类,为从类“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())

Tags: thenameselfinputageiswhatclass
1条回答
网友
1楼 · 发布于 2024-09-27 00:15:47

你应该更喜欢组合而不是继承。主人不是宠物,主人有宠物。我建议采取以下办法:

class Owner:

   def __init__(self,pet, address):
       self.pet = pet
       self.address = address 
pet=Pet()
address = Address()
owner = Owner(pet, address)
#owner.pet

或者宠物有主人:

class PetWithOwner(Pet):

   def __init__(self,owner):
       super(PetWithOwner, self).__init__()
       self.pet = pet

owner = Owner()
pet = PetWithOwner(owner)
#pet.owner

相关问题 更多 >

    热门问题