2017-07-03 36 views
0

我正在尝试为宠物创建一个类,并为类“Pet”继承名称和品种等的所有者创建另一个类。我将如何使用所有者的类Pet1中的宠物名称?如何从对象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()) 

回答

0

你应该比继承更喜欢构图。店主不是 a宠物,店主有宠物宠物。我建议以下方法:

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 
+0

谢谢你非常有帮助:) –