Python properties and built-in properties

Keywords: Python Attribute

property

1. Add getter and setter methods to private properties

class Money(object):
    def __init__(self):
        self.__money = 0

    def getMoney(self):
        return self.__money

    def setMoney(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:Not an integer number")

2. Use property to upgrade getter and setter methods

class Money(object):
    def __init__(self):
        self.__money = 0

    def getMoney(self):
        return self.__money

    def setMoney(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:Not an integer number")
    money = property(getMoney, setMoney)

Operation result:

In [1]: from get_set import Money

In [2]: 

In [2]: a = Money()

In [3]: 

In [3]: a.money
Out[3]: 0

In [4]: a.money = 100

In [5]: a.money
Out[5]: 100

In [6]: a.getMoney()
Out[6]: 100

3. Replace getter and setter methods with property

@Property becomes a property function, which can check the property assignment and ensure the code is clear and short. It has two main functions

Convert method to read-only
Re implement an attribute setting and reading method to make boundary determination

class Money(object):
    def __init__(self):
        self.__money = 0

    @property
    def money(self):
        return self.__money

    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:Not an integer number")

Operation result

In [3]: a = Money()

In [4]: 

In [4]: 

In [4]: a.money
Out[4]: 0

In [5]: a.money = 100

In [6]: a.money
Out[6]: 100

Built in properties

"teachclass.py"

class Person(object):
    pass

Built in properties and methods of classes in Python 3.5

Classic class (old style class). In the early days, if there is no parent class to inherit, there are empty classes in the inheritance

#There is no inherited parent class in py2, which is called classic class. The object is inherited by default in py3
class Person:
    pass

When the subclass does not implement the init method, the default is to automatically call the of the parent class. For example, when defining the init method, you need to manually call the init method of the parent class

__getattribute? Example:

class Itcast(object):
    def __init__(self,subject1):
        self.subject1 = subject1
        self.subject2 = 'cpp'

    #Property access interceptor, log
    def __getattribute__(self,obj):
        if obj == 'subject1':
            print('log subject1')
            return 'redirect python'
        else:   #Comment out these 2 lines during test, subject2 will not be found
            return object.__getattribute__(self,obj)

    def show(self):
        print('this is Itcast')

s = Itcast("python")
print(s.subject1)
print(s.subject2)

Operation result:

log subject1
redirect python
cpp

**__Pit of getattribute**

class Person(object):
        def __getattribute__(self,obj):
            print("---test---")
            if obj.startswith("a"):
                return "hahha"
            else:
                return self.test

        def test(self):
            print("heihei")

    t.Person()
    t.a #Return to hahha
    t.b #It's going to kill the program
        #The reason is: when t.b executes, it will call the Zu getattribute Zu method defined in the Person class, but during the execution of this method
        #if the condition is not satisfied, the program executes the code in else, that is, return self.test. This is the problem because return needs to
        #If the value of self.test is returned, first get the value of self.test, because self is the object of t, so self.test is
        #t.test to get the test attribute of the object T, you will jump to the method getattribute to execute, that is to say
        #The recursive call is generated. Since there is no judgment on when to launch the recursive call, the program will run endlessly
        #Every time you call a function, you need to save some data. As the number of calls increases, the memory runs out, so the program crashes
        #
        # Note: do not call self.xxxx in the __getattribute__ method later.

Posted by PHPdev on Tue, 07 Jan 2020 07:10:26 -0800