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

时间:2017-07-03 11:32:29

标签: python class oop object inheritance

我正在尝试为宠物创建一个类,并为“Pet”类继承名称和品种等的所有者创建另一个类。我如何使用班级中对象Pet1的宠物名称为所有者?

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())

1 个答案:

答案 0 :(得分:0)

你应该更喜欢组合而不是继承。所有者不是宠物,所有者拥有宠物。我建议采用以下方法:

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