1.(静态方法)
class Dog(object):
def __init__(self, name):
self.name = name
@staticmethod
def name(obj):
print(‘%s is name‘%obj)
Dog.name(‘ronghua‘)
@staticmethod静态方法与类本身不存在关系,只是调用的时候需要加类名,不可对类中的其他变量进行操作
2.(类方法)
class Dog(object):
name = ‘alex‘
def __init__(self, name):
self.name = name
@classmethod
def eat(self):
print(‘%s is eating‘%self.name)
dog = Dog(‘ronghua‘)
dog.eat()
@classmethod类方法只调用类里面的变量,不调用实例变量
3.(属性方法)
class Dog(object):
def __init__(self, name):
self.name = name
self.__foods = None
@property #定义属性方法
def eat(self):
print(‘%s is eating %s‘%(self.name, self.__foods))
@eat.setter #属性方法添加参数
def eat(self, food):
self.__foods = food
print(‘%s is eating %s‘%(self.name, self.__foods))
@eat.deleter #属性方法的删除
def eat(self):
del self.__foods
dog = Dog(‘shuhua‘)
dog.eat 这是属性变量,因此调用时不需要()
dog.eat = ‘包子‘ #传入参数
dog.eat
del dog.eat #属性变量中的删除
dog.eat #这里会出现报错,因为不存在self.__foods 变量
原文地址:https://www.cnblogs.com/my-love-is-python/p/9101925.html