python中的私有属性,@修饰器以及静态方法、静态类示例说明
python中的私有属性和私有方法
私有属性和方法的定义
如果想要在Python中定义类的私有属性或者私有方法,在属性或者方法定义名称前面加上 __ 即可。但是Python中并没有真正意义上的私有,只是在给属性或者方法命名时对名称做了一些特殊处理,使得外界无法访问到。
如何访问
在访问的私有属性或者方法前面加上 _类名 即可, 例如_testClass__privateAttr。
python中的property修饰器
@property
将Python中的函数当做属性进行访问,从而可以提供更加友好的访问方式。
只有@property表示只读
@name.setter
同时有@property 和 @name.setter表示可读写。
@name.deleter
同时有@property,@name.setter 和 @name.deletter表示可读可写可删除。
python中的静态方法和类方法
静态方法@staticmethod
静态方法没有隐形参数
类方法@classmethod
类方法中的隐参cls,当调用函数的主体是类,那么cls就是这个类。当调用函数的主体时对象,那么cls就是这个对象的类型。
此外,示例代码如下:
class testClass:
def __init__(self, str):
self.name = str
self.__privateAttr = "this is a private attribute"
def __private_function(self):
logging.info(" private function: %s" % self.__privateAttr)
@property
def testAttr(self):
if hasattr(self, '_attr'):
return self._attr
else:
raise ValueError("testAttr should be set first!")
@testAttr.setter
def testAttr(self, value):
self._attr = value
@testAttr.deleter
def testAttr(self):
if hasattr(self, "_attr"):
del self._attr
else:
raise ValueError("testAttr not found before deletion!")
@classmethod
def class_test(cls, time):
# cls 如果是类调用该函数,那么cls就是这个类
# 如果是对象调用该函数,那么cls就是这个对象的类型
logging.info(cls)
logging.info(time)
@staticmethod
def static_test(time):
# 静态方法没有隐形参数
logging.info("static test %s" % (time))
if __name__ == "__main__":
tc = testClass("test Class")
logging.info(tc._testClass__privateAttr)
tc._testClass__private_function()
tc.testAttr = "testAttr"
logging.info(tc.testAttr)
del tc.testAttr
testClass.class_test("class_test")
testClass.static_test("static_test")