知识点:
1.property 作用 :相当于把类的方法封装,开发者在设置属性时更方便,还可以隐藏属性名字。
2.传统的调用 一个对象中的私有属性self.__x 可以采用setter 和 getter 方法 但是相对比较繁琐
3.property 第一种用法 num = property(getNum,setNum) ,当程序执行 num = 1,程序会自动调用setNum方法 当程序执行 print(num) 时 程序会自动调用 getNum方法
4.property 第二种用法
@property
def money(self):
return self.num
@money.setter
def money(self,new_num)
self.num = new_num
也可以通过money = 1 print(money) 访问私有元素
5. 在这里再补充一下私有问题
__x 私有属性 只有本类的对象可用
_x 禁止导入,但是类的对象和子类可用
__x__ 魔法方法 由python 自己定义 有特殊方法
x__ 用来解决关键字冲突问题。
# # class Test(object):
# # def __init__(self):
# # self.__num = 10
# # def getNum(self):
# # return self.__num
# # def setNum(self,newnum):
# # self.num = newnum
# # t = Test()
# # print(t.getNum())
# # t.setNum(50)
# # print(t.getNum())
# class Test(object):
# def __init__(self):
# self.__num = 10
# def getNum(self):
# return self.__num
# def setNum(self,newnum):
# self.__num = newnum
# num = property(getNum,setNum)
# t = Test()
# t.num = 2
# print(t.num)
#property作用: 相当于把函数方法封装起来,开发者设置属性更加方便
class Test(object):
def __init__(self):
self.__num = 10
@property
def t_num(self):
return self.__num
@t_num.setter
def t_num(self,newnum):
self.__num = newnum
t = Test()
t.t_num = 1
print(t.t_num)