This is the second day of my participation in the August Text Challenge.More challenges in August

introduce

The Python language has a number of built-in functions that put soul into code, also known as “syntactic sugar”. Today we use the built-in property function, which encapsulates methods as properties.

The business case

There are a lot of if judgments in the Query method of DataQuery class, which need tedious query and the function is bloated

class DataQuery(object) :
    """ Data query ""
    def query(self, *args) :
        if args[0] = ='data1':
            print('data1')
        elif args[0] = ='data2':
            print('data2')

q = DataQuery()
q.query('data1')
Copy the code

Use the built-in @property property

The Query class encapsulates two attributes, and other functions, when called or used, elegantly present a Query for a property.

class Query(object) :
    """ Database class """
    @property
    def data1(self) :
        print('data1')

    @property
    def data2(self) :
        print('data2')

q = Query()
q.data1
Copy the code

In conclusion, using the @property attribute for encapsulation makes the code more elegant and readable. More Python features are coming. Please pay more attention to ~~