2017-07-03 37 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

謝謝你非常有幫助:) –