Python---静态方法,类方法,属性方法

1.静态方法

#静态方法:只是名义上归类管理,实际上在静态方法中访问不了类和实例
class Person(object):
    def __init__(self,name):
        self.name=name
    @staticmethod   #截断类与函数关系,不能调用类变量
    def eat():
        print("%s is eating %s"%('ddd','dd'))
d=Person("XiaoMing")
d.eat()
 
  

若想调用self,则需自行传实例,如下:

#静态方法:只是名义上归类管理,实际上在静态方法中访问不了类和实例
class Person(object):
    def __init__(self,name):
        self.name=name
    @staticmethod   #截断类与函数关系,不能调用类变量
    def eat(self):
        print("%s is eating %s"%(self.name,'dd'))
d=Person("XiaoMing")
d.eat(d)

2.类方法

#类方法:只能访问类变量,不能访问实例变量
class Person(object):
    A='Xiaoxiong'
    def __init__(self,name):
        self.name=name
    @classmethod
    def eat(self):
        print("%s is eating %s"%(self.A,'ddd'))
d=Person("XiaoMing")
d.eat()

3.属性方法 (作用 隐藏实现细节)

#属性方法
#1.将函数方法变为一个静态属性
class Person(object):
    def __init__(self,name):
        self.name=name
    @property
    def eat(self):
        print("%s is eating %s"%(self.name,'dd'))
d=Person("XiaoMing")
d.eat
#2.修改属性
class Person(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):
        print("set to food:",food)
        self.__food=food
d=Person("XiaoMing")
d.eat='baozi'
d.eat
#3.删除属性
class Person(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):
        print("set to food:",food)
        self.__food=food
    @eat.deleter     #删除私有属性self.__food
    def eat(self):
        del self.__food
        print("删完了")
d=Person("XiaoMing")
d.eat
d.eat='baozi'
d.eat
del d.eat  #删除函数方法私有属性后即可删除函数
d.eat

你可能感兴趣的:(python基础)