python静态方法、类方法

常规:

 class Dog(object):
def __init__(self,name):
self.name=name def eat(self):
print('%s is eating'%self.name) d1=Dog('lele')
d1.eat()

1.静态方法:名义上由类管理,而实际在调用时,需要手动把实例对象传进去作参数

 class Dog(object):
def __init__(self,name):
self.name=name
@staticmethod
def eat(self):
print('%s is eating'%self.name) d1=Dog('lele')
d1.eat(d1)

2.类方法:只能访问类变量,不能访问实例变量

 class Dog(object):
name='xiaomei'
def __init__(self,name):
self.name=name @classmethod
def eat(self):
print('%s is eating'%self.name) d1=Dog('lele')
d1.eat()

实例变量name='lele',类变量name='xiaomei'。

调用结果为:xiaomei is eating

3.属性方法:把一个方法变为一个静态属性(用途:用户只需要知道查询结果(调用属性),而复杂的实现过程不需要用户知道。eg:第三方查询航班)

 class Dog(object):
def __init__(self,name):
self.name=name @property
def eat(self):
print('%s is eating'%self.name) d1=Dog('lele')
d1.eat

lele is eating

若要增加参数,可以通过 @属性方法名.setter  来实现

class Dog(object):
def __init__(self,name):
self.name=name
self.__food=None
#将一个方法变为静态属性
@property
def eat(self):
print('%s is eating %s' % (self.name,self.__food)) #更改属性方法
@eat.setter
def eat(self,food): #增加了参数
self.__food=food
print('%s is eating %s' % (self.name, self.__food))
#删除属性方法
@eat.deleter
def eat(self):
del self.__food
print('已删除') d1=Dog('lele')
d1.eat
d1.eat='gutou' #变成静态属性后,注意赋值方式
d1.eat
del d1.eat

lele is eating None
lele is eating gutou
lele is eating gutou
已删除

上一篇:mysql+mybatis 插入可递增字段库表操作


下一篇:log4j警告:WARN Please initialize the log4j system properly 的解决方法