面向对象之property

Posted 强仔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象之property相关的知识,希望对你有一定的参考价值。

property功能

  1. 以调用数据属性的方式(不用加括号)调用方法
  2. 方法定义成数据属性(方法本应该是动词)

 

# 定义property之前
class People:
    def __init__(self,name,age,height,weight):
        self.name=name
        self.age=age
        self.height=height
        self.weight=weight
    def bmi(self):
        return self.weight /(self.height*self.height)

whq=People(whq,20,1.65,65)
whq.height=1.82
print(whq.bmi())

# 定义property之后
class People:
    def __init__(self,name,age,height,weight):
        self.name=name
        self.age=age
        self.height=height
        self.weight=weight
    @property
    def bmi(self):
        return self.weight /(self.height*self.height)

whq=People(whq,20,1.65,65)
whq.height=1.82
print(whq.bmi)#此处不用加括号调用

 

以上是关于面向对象之property的主要内容,如果未能解决你的问题,请参考以下文章

Python 面向对象 之 @property

面向对象之property

面向对象之—property,staticmethod

python面向对象之property用法补充(getter,setter,deleter)

面向对象之封装 及@property装饰器使用

Python--面向对象的程序设计之继承实现的原理(继承顺序)封装property