首页 > 其他 > 详细

对象的属性隐藏

时间:2018-06-18 00:07:41      阅读:199      评论:0      收藏:0      [点我收藏+]
1.隐藏对象的属性
class Dog:
def set_age(self,new_age):
if new_age>0 and new_age<=100:
self.age = new_age
else:
self.age = 0

def get_age(self):
return self.age

dog = Dog()
#dog.age = -10
#dog.name = "小白"

#print(dog.age)


dog.set_age(-10)
age = dog.get_age()
print(age)

#dog.get_name()

dog.age = -10
print(dog.age)

2.隐藏对象的属性,私有属性
class Dog:

def __init__(self, new_name):
self.name = new_name
self.__age = 0#定义了一个私有的属性,属性的名字是__age

def set_age(self,new_age):
if new_age>0 and new_age<=100:
self.__age = new_age
else:
self.__age = 0

def get_age(self):
return self.__age

dog = Dog("小白")
#dog.age = -10
#dog.name = "小白"

#print(dog.age)


dog.set_age(-10)
age = dog.get_age()
print(age)

#dog.get_name()

#dog.__age = -10
print(dog.__age)

对象的属性隐藏

原文:https://www.cnblogs.com/loser1949/p/9194142.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!