我是OOP新手,这是我创建Python类的第一次尝试。我试图使我的3个变量私有化,以便只有方法更新信息(强制封装)。似乎如果我从类中删除setters和getters方法,它对我的代码没有影响(一定是初始化器方法在做这项工作吗?)。我能做些什么来改善这一点?谢谢。在
编辑-我已经更新了我的代码并删除了初始化。我的吸气筒现在不工作了。在#Instantiate a new Pet Instance.
myPet = Pet()
#Get input from user.
myPet.setName = input("Enter the pet's name: ")
myPet.setTypes = input("Enter the pet's type (Dog, Cat, Bird, etc.): ")
myPet.setAge = input("Enter the pet's age (in years): ")
while myPet.setAge.isalpha():
print()
print("Age cannot contain numbers. Try again.")
myPet.setAge = input("Enter the pet's age (in years): ")
#Call the showPetInfo module using new instanced object.
myPet.showPetInfo()
class Pet:
#Fields of the Pet Class.
__PetName = ""
__PetType = ""
__PetAge = ""
#Setter methods.
def setName(self,name):
self.__PetName = name
def setTypes(self,types):
self.__PetType = types
def setAge(self,age):
self.__PetAge = age
#Getter methods.
@property
def getName(self):
return self.__PetName
@property
def getType(self):
return self.__PetType
@property
def getAge(self):
return self.__PetAge
def showPetInfo(self):
print("\n \n \n \n")
print("Here is your pet's information. Your pet's name is {}, it is a {} and it is {} years old.".format(self.getName,self.getType,self.getAge))
main()