Python中类的使用(5私有属性)
16lz
2021-01-22
class Person(object):
def run(self):
print("run")
def eat(self, food):
print("eat" + food)
def __init__(self,name,age,height,weight,money):
self.name=name
self.age=age
self.height=height
self.weight=weight
self.__money=money #money==_Person__money
#内部可以直接访问加__的属性,外部无法直接访问
#通过自定义的方法实现对私有属性的赋值和取值
def setMoney(self,money):#赋值
#数据过滤
if money<0:
money=0
self.__money=money
def getMoney(self):#取值
return self.__money
#只有在属性前加两个下划线(__),才能变为私有属性,
# 让内部属性不被外部直接访问,
per1=Person("lili",20,175,50,1000)
per1.age=10
print(per1.age)
#per1.money=1000#程序运行时赋值
#print(per1.__money)#外部无法访问
per1.setMoney(100) #修改money的值,等同于per1._Person__money=100
per1.getMoney()
print(per1.getMoney())
#不能直接访问per.__money是因为Python解释器把__money变为了
# _Person__money,仍然可以用_Person__money去访问,只是不建议使用
# 不同版本的解释器可能存在解释的变量名不一致
# per1._Person__money=1#可以直接修改内部money的值
更多相关文章
- 'module'对象没有属性'views' django错误
- AttributeError:“MatrixFactorizationModel”对象没有属性“sav
- 在不知道序列长度的情况下,在Python中展开多个赋值
- Python------类的结构细分,异常处理,方法,属性
- Python进阶----类的结构(公有成员 , 私有成员(私有属性,私有方法
- AttributeError:'Flask'对象没有属性'login_manager' - Login_Ma
- 关于Python的属性、参数、方法的解释、区别
- 在Python / IPython解释器中为单个下划线_赋值
- python函数的属性