Object oriented property

Posted by arn_php on Mon, 11 Nov 2019 19:58:14 +0100

1.property

1.1 what is property

Property is a special property that is accessed by executing a function and returning a value
Characteristic:
1. When executing a function, you do not need to call obj.func(). You can directly call obj.func as a variable to execute a function
2. It cannot be assigned a value

For example: BMI value=Body weight ( kg)÷height^2(m)
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)

p1=People('egon',75,1.85)
print(p1.bmi)
For example: circumference and area of a circle
import math
class Circle:
    def __init__(self,radius): #radius of circle
        self.radius=radius

    @property
    def area(self):
        return math.pi * self.radius**2 #Calculated area

    @property
    def perimeter(self):
        return 2*math.pi*self.radius #Circumference calculation

c=Circle(10)
print(c.radius)
print(c.area) #You can access the area just like you can access the data attribute, which will trigger the execution of a function and dynamically calculate a value
print(c.perimeter) #Ditto
'''
//Output results:
314.1592653589793
62.83185307179586
'''
"There area and perimeter Cannot be assigned"
c.area=3 #Assign value to property area
'''
//Throw exception:
AttributeError: can't set attribute
'''

1.2 why to use property

After defining the function of a class as a property, obj.name cannot realize that its name is calculated by executing a function when the object is used again. The usage of this property follows the principle of unified access

ps: there are three ways of object-oriented encapsulation:
[public]
In fact, it's not encapsulated, it's open to the public
[protected]
This way of encapsulation is not open to the public, but it is open to friends or subclasses (I don't know why we don't say "daughter", just like "parent" originally means "parents", but Chinese is called "father")
[private]
This kind of encapsulation is not open to anyone

Python does not have built-in public,protected,private syntax. In Java, all data will be set as private, and then set and get methods are provided to set and get. In Python, it can be realized through property

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Foo:
    def __init__(self,val):
        self.__NAME=val #Hide all data attributes

    @property
    def name(self):
        return self.__NAME #obj.name accesses self. \

    @name.setter
    def name(self,value):
        if not isinstance(value,str):  #Type check before setting value
            raise TypeError('%s must be str' %value)
        self.__NAME=value #After passing the type check, store the value value in the real location self. \

    @name.deleter
    def name(self):
        raise TypeError('Can not delete')
f=Foo('egen')
print(f.name)

f.name="10"
print(f.name)

//Result
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
egen
10

Process finished with exit code 0
f.name=10
//Result
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 23, in <module>
    f.name=10
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 15, in name
    raise TypeError('%s must be str' %value)
TypeError: 10 must be str

Process finished with exit code 1
del f.name

//Result
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 23, in <module>
    del f.name
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 20, in name
    raise TypeError('Can not delete')
TypeError: Can not delete

Process finished with exit code 1

Topics: Python Attribute Java