""" clerker.py 类 edit:geovindu,Geovin Du date:20230672 IDE:PyCharm 2023.1.2 clerker.__dict__ 窥探私有属性 私用属性 clerker._Clerker.__age=-1 clerker.__age=-1 """ import sys import os class Clerker(object): """ 类的封装 """ salary=30 #定义类的公有属性 _salary2=20 #定义类的保护属性 __salary3=50 #定义类的私有属性 def __init__(self,name:str,age:int): """ :param name: :param age: """ self._name=name #公有属性 self.__age=age #私用属性,需要通过(函数)setter,getter 设置和访问 @property # @property装饰getter方法 get ,set 名字相符 def Age(self): """ :return: """ return self.__age @Age.setter def Age(self,age): #@方法名.setter 设置 """ :param age: :return: """ if age>0: self.__age=age def __getage(self): """ :return: """ print(f"我是{self._name},今年{self.__age}岁") return self.__age def setName(self,name): """ :param name: :return: """ self._name=name def getName(self): """ :return: """ return self._name def setAge(self,age): """ :param age: :return: """ if(age>0): self.__age=age def getAge(self): """ :return: """ return self.__age
调用:
#私有属性也可以处理 cl=Clerker.Clerker("geovindu",25) print(cl.getAge()) print(cl.__dict__) #查看属性 print(Clerker.__dict__) #查看方法 cl._Clerker__age=20 print(cl.Age) print(cl._Clerker__getage()) print(Clerker.Clerker.salary) print(Clerker.Clerker._salary2)
标签:.__,return,name,python,age,Clerker,objct,property,self From: https://www.cnblogs.com/geovindu/p/17520468.html