table of Contents
Class three decorator
Method decorative
@classmethod ---> decorative methods, without self property, only property class cls
@staticmethod ---> decorative static method, neither self attributes, it does not have the properties of class cls
@property ---> a method to disguise property
A, @ classmethod
In a class method without object attributes, but use the static properties, then this method is a class method, is decorated classmethod decorator method, there is a default parameter cls, this parameter is the current class!
class A:
__count = 0
def __init__(self,name):
self.name = name
self.__add_count() #只要执行init方法实例化对象就会产生调用 __add_count(),从而对静态属性__count操作
@classmethod
def __add_count(cls): #私有方法
cls.__count += 1 #让这个方法只能在内部被使用
@classmethod #被classmethod装饰器装饰的方法,都有一个默认的参数,这个参数就是当前类
def show_count(cls):
return cls.__count
print(A.show_count()) # 0 类调用show_count方法查看类的静态属性
Sheldon = A('Sheldon') # 实例化一个对象
print(Sheldon.show_count()) # 1 对象调用show_count方法查看类的静态属性
可以看出调用类方法,可以用对象调用,也可以使用类调用
但是这个方法默认参数永远是当前类的命名空间,而不是对象的
Two, @ staticmethod decorator decoration static method
If the method does not use a class object properties do not use the static properties - Static method, @ staticmethod decoration of this method is actually this way is a common function.
Common method | Class Methods | Static method | |
---|---|---|---|
The default parameters | self | cls | no |
Variable operation | Operation object properties | Operation class attributes | Neither the operation object properties, nor the operation class attributes |
Namespace belongs | class | class | class |
Call the method | Objects | Class / object | Class / object |
Decorator | @classmethod | @staticmethod |
Three. @ Property attribute to a method of disguise
@ Name.setter note, what setter decorative function named, then this function must not modify the properties of the same name in this function
@ Name.deleter caller method to delete properties
示例1
from math import pi
class Circle:
def __init__(self,r):
self.r = r
@property # 把一个方法伪装成属性
def area(self): # 被property装饰器装饰的方法不能传递除self以外的参数
return pi*self.r**2
@property
def perimeter(self):
return self.r*pi*2
c1 = Circle(5)
print(c1.area)
c1.r = 10
print(c1.area) 调用的时候不用加()
class Person:
def __init__(self,name):
self.__name = name # 不让外部随便修改
@property
def name(self):
return self.__name
Sheldon = Person('Sheldon')
print(Sheldon.name) #这样写起到不容易被别人修改的作用