Python9-封装-day26(大年初三)
作者:互联网
class Room: def __init__(self,name,length,width): self.__name = name self.__length = length self.__width = width def get_name(self): return self.__name def set_name(self,newName): if type(newName) is str and newName.isdigit() == False: self.__name = newName def area(self): return self.__length * self.__width jin = Room('金老板',2,1) print(jin.area()) jin.set_name('2') print(jin.get_name())
会用到私有属性这个概念的场景
隐藏起一个属性,不想让类的外部调用
我想保护这个属性,不想让属性随意被改变
我想保护这个属性不被子类继承
# property 内置装饰器函数,只在面向对象中使用 from math import pi class Circle: def __init__(self,r): self.r = r @property def perimeter(self): return 2*pi*self.r @property def area(self): return self.r**2*pi c1 = Circle(5) print(c1.area) #圆的面积 print(c1.perimeter) #圆的周长 78.53981633974483 31.41592653589793
class Person: def __init__(self,name): self.__name = name @property def name(self): return self.__name + 'sb' @name.setter def name(self,new_name): self.__name = new_name tiger = Person('tim') print(tiger.name) tiger.name = '全班' print(tiger.name) timsb 全班sb
标签:__,.__,name,self,day26,Python9,大年初三,print,def 来源: https://www.cnblogs.com/zhangtengccie/p/10354456.html