Function and object oriented of python

Keywords: Python Back-end

1 function

1.1 function basis

  • definition
 def Function name():
     Code 1
     Code 2
     ...
  • call
    Function name ()
  • Documentation for functions
  def Function name():
      """ Function description document """
  • View the documentation for the function
  help(Function name)

1.2 scope of variable

  • local variable

    • The so-called local variables are variables defined inside the function body, that is, they only take effect inside the function body.
  • global variable

    • The so-called global variable refers to the variable that can take effect both inside and outside the function.
  • How to modify a global variable inside a function body?

a = 100
def testA():
    print(a)
def testB():
    # Global keyword declares that a is a global variable
    global a
    a = 200
    print(a)
testA()  # 100
testB()  # 200
print(f'global variable a = {a}')  # Global variable a = 200

1.3 return value of function

  • return a, b. when multiple data are returned, the default is tuple type.
  • Return can be followed by a list, tuple, or dictionary to return multiple values.

1.4 parameters of function

1.4.1 location parameters

  • Positional parameters: when calling a function, parameters are passed according to the parameter positions defined by the function.
    • The order and number of parameters passed and defined must be consistent.

1.4.2 keyword parameters

  • It is specified in the form of "key = value". It can make the function clearer and easier to use, and eliminate the sequence requirements of parameters.
def user_info(name, age, gender):
    print(f'What's your name{name}, Age is{age}, Gender is{gender}')
user_info('Rose', age=20, gender='female')
user_info('Xiao Ming', gender='male', age=16)
  • When calling a function, if there is a positional parameter, the positional parameter must precede the keyword parameter, but there is no order between the keyword parameters.

1.4.3 default parameters

  • Default parameters are also called default parameters. They are used to define functions and provide default values for parameters. The value of the default parameter may not be passed when calling a function
  • All positional parameters must appear before the default parameters, including function definitions and calls
def user_info(name, age, gender='male'):
    print(f'What's your name{name}, Age is{age}, Gender is{gender}')
user_info('TOM', 20)
user_info('Rose', 18, 'female')

1.4.4 variable length parameters

  • Package location transfer
def user_info(*args):
    print(args)


# ('TOM',)
user_info('TOM')
# ('TOM', 18)
user_info('TOM', 18)

Note: all parameters passed in will be collected by the args variable, which will be combined into a tuple according to the position of the parameters passed in. Args is a tuple type, which is package position transfer.

  • Package keyword delivery
def user_info(**kwargs):
    print(kwargs)


# {'name': 'TOM', 'age': 18, 'id': 110}
user_info(name='TOM', age=18, id=110)

To sum up: both package location transfer and package keyword transfer are a process of package grouping.

1.5 unpacking and exchange variable values

1.5.1 unpacking

  • Unpacking: tuples
def return_num():
    return 100, 200


num1, num2 = return_num()
print(num1)  # 100
print(num2)  # 200
  • Unpacking: Dictionary
dict1 = {'name': 'TOM', 'age': 18}
a, b = dict1

# Unpack the dictionary and take out the key of the dictionary
print(a)  # name
print(b)  # age

print(dict1[a])  # TOM
print(dict1[b])  # 18

1.5.2 exchange variable values

a, b = 1, 2
a, b = b, a
print(a)  # 2
print(b)  # 1

1.6 references

  • In python, values are passed by reference.

  • We can use id() to determine whether two variables are references to the same value.

  • We can understand the id value as the address identification of that memory.

1.6.1 reference as argument

def test1(a):
    print(a)
    print(id(a))

    a += a

    print(a)
    print(id(a))


# int: the id value is different before and after calculation
b = 100
test1(b)

# List: the id values before and after calculation are the same
c = [11, 22]
test1(c)

1.6.2 variable type and immutable type

The so-called variable type and immutable type mean that data can be modified directly. If it can be modified directly, it is variable, otherwise it is immutable

  • Variable type
    • list
    • Dictionaries
    • aggregate
  • Immutable type
    • integer
    • float
    • character string
    • tuple

1.7 lambda expression

1.7.1 lambda syntax

  • lambda argument list: expressions
  • The parameters of lambda expression are optional, and the parameters of function are fully applicable in lambda expression.
  • lambda expressions can accept any number of parameters, but can only return the value of one expression.

1.7.2 parameter form of lambda

  • No parameters
fn1 = lambda: 100
print(fn1())
  • One parameter
fn1 = lambda a: a
print(fn1('hello world'))
  • Default parameters
fn1 = lambda a, b, c=100: a + b + c
print(fn1(10, 20))
  • Variable parameter: * args
fn1 = lambda *args: args
print(fn1(10, 20, 30))

Note: after the variable parameters here are passed into lambda, the return value is tuple.

  • Variable parameters: * * kwargs
fn1 = lambda **kwargs: kwargs
print(fn1(name='python', age=20))

1.7.3 application of lambda

  • lambda with judgment
fn1 = lambda a, b: a if a > b else b
print(fn1(1000, 500))
  • The list data is sorted by the value of the dictionary key
students = [
    {'name': 'TOM', 'age': 20},
    {'name': 'ROSE', 'age': 19},
    {'name': 'Jack', 'age': 22}
]

# Sort by name value in ascending order
students.sort(key=lambda x: x['name'])
print(students)

# Sort by name value in descending order
students.sort(key=lambda x: x['name'], reverse=True)
print(students)

# Sort in ascending order by age value
students.sort(key=lambda x: x['age'])
print(students)

1.8 higher order function

  • The function is passed in as a parameter. Such a function is called a high-order function, which is the embodiment of functional programming. Functional programming refers to this highly abstract programming paradigm.
def sum_num(a, b, f):
    return f(a) + f(b)


result = sum_num(-1, 2, abs)
print(result)  # 3
  • Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.

1.8.1 built in high-order function

  • map(func, lst):
    • Parameter 1: function
    • Parameter 2: container
    • Return value: new container
  • reduce(func,lst)
    • Parameter 1: function
    • Parameter 2: container
    • Return value: value
  • filter(func, lst)
    • Parameter 1: function
    • Parameter 2: container
    • Return value: container

2. Object oriented

Type 2.1

There are two classes in Python 2: Classic class and new class

  • grammar
class Class name():
    code
    ......

Note: the class name shall meet the identifier naming rules and follow the naming habit of big hump.

  • experience
class Washer():
    def wash(self):
        print('I can wash clothes')
  • Expansion: Classic

A class that does not derive from any built-in type is called a classic class

class Class name:
    code
    ......

2.1.1 creating objects

Object, also known as instance.

  • grammar
Object name = Class name()

2.1.2 self

self refers to the object that calls the function

2.2 adding and obtaining object attributes

  • Add object properties outside the class
Object name.Attribute name = value
  • Get object properties outside class
Object name.Attribute name
  • Class to get object properties
self.Attribute name
  • Class to set object properties
self.Attribute name=value

2.3 magic methods

In Python__ xx__ The function of () is called magic method, which refers to the function with special function.

2.3.1 __init__()

  • Initialize object

  • Called by default when creating an object

  • __ init__ The self parameter in (self) does not need to be passed by the developer. The python interpreter will automatically pass the current object reference.

  • You can also take other parameters__ init__(self, width, height)

2.3.2 __str__()

  • When using print to output an object, the memory address of the object is printed by default.
  • If the class is defined__ str__ Method, the data return ed from this method will be printed.

2.3.3 __del__()

  • When an object is deleted, the python interpreter also calls by default__ del__ () method.

2.4 succession

A class that does not derive from any built-in type is called a classic class.

class Class name:
    code
    ......
  • Expansion 2: new type
class Class name(object):
  code
  • In Python, all classes inherit the object class by default. The object class is the top-level class or base class; Other subclasses are called derived classes.

2.4.1 multi inheritance

class Prentice(School, Master):
    pass
  • Note: when a class has multiple parent classes, the properties and methods with the same name of the first parent class are used by default.

2.4.2 subclasses call methods and properties of the parent class with the same name

class Master(object):
    def __init__(self):
        self.kongfu = '[Gufa pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')


class School(object):
    def __init__(self):
        self.kongfu = '[Dark horse pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')


class Prentice(School, Master):
    def __init__(self):
        self.kongfu = '[Original pancake fruit formula]'

    def make_cake(self):
        # If the properties and methods of the parent class are called first, the parent class property will override the class property. Therefore, before calling the property, call the initialization of your own child class
        self.__init__()
        print(f'application{self.kongfu}Making pancake fruit')

    # Invoke the parent class method, but to ensure that the property that is called is also a parent class, we must call the initialization of the parent class before calling the method.
    def make_master_cake(self):
        Master.__init__(self)
        Master.make_cake(self)

    def make_school_cake(self):
        School.__init__(self)
        School.make_cake(self)


daqiu = Prentice()

daqiu.make_cake()

daqiu.make_master_cake()

daqiu.make_school_cake()

daqiu.make_cake()

2.4.3 multi layer inheritance

class Master(object):
    def __init__(self):
        self.kongfu = '[Gufa pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')


class School(object):
    def __init__(self):
        self.kongfu = '[Dark horse pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')


class Prentice(School, Master):
    def __init__(self):
        self.kongfu = '[Original pancake fruit formula]'

    def make_cake(self):
        self.__init__()
        print(f'application{self.kongfu}Making pancake fruit')

    def make_master_cake(self):
        Master.__init__(self)
        Master.make_cake(self)

    def make_school_cake(self):
        School.__init__(self)
        School.make_cake(self)


# Disciple
class Tusun(Prentice):
    pass


xiaoqiu = Tusun()

xiaoqiu.make_cake()

xiaoqiu.make_school_cake()

xiaoqiu.make_master_cake()

2.4.2 supper()

  • Use super() to automatically find the parent class. Call order follows__ mro__ The order of class properties. It is more suitable for single inheritance.
class Master(object):
    def __init__(self):
        self.kongfu = '[Gufa pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')


class School(Master):
    def __init__(self):
        self.kongfu = '[Dark horse pancake fruit formula]'

    def make_cake(self):
        print(f'application{self.kongfu}Making pancake fruit')

        # Method 2.1
        # super(School, self).__init__()
        # super(School, self).make_cake()

        # Method 2.2
        super().__init__()
        super().make_cake()


class Prentice(School):
    def __init__(self):
        self.kongfu = '[Original pancake fruit technology]'

    def make_cake(self):
        self.__init__()
        print(f'application{self.kongfu}Making pancake fruit')

    # Subclasses call the methods and properties of the parent class with the same name: encapsulate the properties and methods of the parent class with the same name again
    def make_master_cake(self):
        Master.__init__(self)
        Master.make_cake(self)

    def make_school_cake(self):
        School.__init__(self)
        School.make_cake(self)

    # Call the property and method with the same name of the parent class at once
    def make_old_cake(self):
        # Method 1: code redundancy; If the parent class name changes, the code here needs to be modified frequently
        # Master.__init__(self)
        # Master.make_cake(self)
        # School.__init__(self)
        # School.make_cake(self)

        # Method 2: super()
        # Method 2.1 super (current class name, self). Function ()
        # super(Prentice, self).__init__()
        # super(Prentice, self).make_cake()

        # Method 2.2 super(). Function ()
        super().__init__()
        super().make_cake()


daqiu = Prentice()

daqiu.make_old_cake()

2.5 private rights

2.5.1 defining private attributes and methods

  • Set private permission: set an instance property or instance method that does not inherit from subclasses.
  • Precede the property name and method name with two underscores _.

2.5.2 obtaining and modifying private attribute values

  • In Python, the function name get is generally defined_ XX is used to obtain private properties and define set_xx is used to modify private property values.

Class 2.6 attributes

2.6.1 setting and accessing class properties

  • Class attribute is the attribute owned by the class object, which is shared by all instance objects of the class.
  • Class properties can be accessed using class objects or instance objects.
class Dog(object):
    tooth = 10


wangcai = Dog()
xiaohei = Dog()

print(Dog.tooth)  # 10
print(wangcai.tooth)  # 10
print(xiaohei.tooth)  # 10

Advantages of class properties

  • Class properties are defined when a recorded item of data is always consistent.
  • Instance properties require each object to open up a separate memory space for recording data, while class properties are shared by the whole class, occupying only one memory, which saves more memory space.

2.6.2 modifying class attributes

Class properties can only be modified through class objects, not instance objects. If class properties are modified through instance objects, it means that an instance property is created.

class Dog(object):
    tooth = 10


wangcai = Dog()
xiaohei = Dog()

# Modify class properties
Dog.tooth = 12
print(Dog.tooth)  # 12
print(wangcai.tooth)  # 12
print(xiaohei.tooth)  # 12

# You cannot modify properties through objects. If you do, you will actually create an instance property
wangcai.tooth = 20
print(Dog.tooth)  # 12
print(wangcai.tooth)  # 20
print(xiaohei.tooth)  # 12

2.7 instance properties

class Dog(object):
    def __init__(self):
        self.age = 5

    def info_print(self):
        print(self.age)


wangcai = Dog()
print(wangcai.age)  # 5
# print(Dog.age)  # Error: instance property cannot be accessed through class
wangcai.info_print()  # 5

Class 2.8 method

2.8.1 characteristics of class I methods

  • The decorator @ classmethod needs to be used to identify it as a class method. For a class method, the first parameter must be a class object. Generally, cls is used as the first parameter.

2.8.2 usage scenarios of class methods

  • When class objects need to be used in methods (such as accessing private class properties, etc.), class methods are defined
  • Class methods are generally used in conjunction with class properties
class Dog(object):
    __tooth = 10

    @classmethod
    def get_tooth(cls):
        return cls.__tooth


wangcai = Dog()
result = wangcai.get_tooth()
print(result)  # 10

2.9 static method

2.9.1 characteristics of static method

  • It needs to be decorated through the decorator @ staticmethod. Static methods do not need to pass class objects or instance objects (formal parameters do not have self/cls).
  • Static methods can also be accessed through instance objects and class objects.

2.9.2 usage scenario of static method

  • Static methods are defined when neither instance objects (such as instance objects and instance properties) nor class objects (such as class properties, class methods, creating instances, etc.) need to be used in methods
  • Canceling unnecessary parameter passing is helpful to reduce unnecessary memory occupation and performance consumption
class Dog(object):
    @staticmethod
    def info_print():
        print('This is a dog class used to create dog instances....')


wangcai = Dog()
# Static methods can be accessed using both objects and classes
wangcai.info_print()
Dog.info_print()

Posted by OOP on Fri, 12 Nov 2021 14:23:33 -0800