欢迎第 Free Counters个访客

python中的@property

@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/getter也是需要的

class People:
    def __init__(self,name,weight,height):
        self.__name=name
        self.weight=weight
        self.height=height
    @property
    def bmi(self):
        return self.weight / (self.height**2)
    @bmi.deleter
    def bmi(self):
        del self.__name

p1=People('wang',67,1.7)
del p1.bmi
print(p1.__name)

@bmi.deleter相当于一个接口,想要直接删除私有属性是不可以的,要有这么一个接口.删除私有属性

说明:同一属性的三个函数名要相同。(例子中都是bim)

 

@bmi.setter是修改

def bmi(self,新的参数)

classmethod

 

class Classmethod_Demo():
    role = 'dog'

    @classmethod
    def func(cls):
        print(cls.role)

Classmethod_Demo.func()

 

staticmethod

 

class Staticmethod_Demo():
    role = 'dog'

    @staticmethod
    def func():
        print("当普通方法用")
Staticmethod_Demo.func()

 

posted @ 2018-01-20 18:55  阿强Wwlt  阅读(181)  评论(0编辑  收藏  举报