python封装的方法_Python类和封装方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值