Day018 - advanced object oriented

Addition, deletion, modification and query of object attributes

class Student:
    def __init__(self, stu_id, name, age=18):
        self.stu_id = stu_id
        self.name = name
        self.age = age

    # It is called automatically when the object of the current class is printed, and the return value of this method is taken as the return result of this kind of object
    # The return value must be a string
    def __repr__(self):
        return f'<{str(self.__dict__)[1:-1]}>'

    def show_message(self):
        return [self.stu_id, self.name, self.age]
stu1 = Student('000', 'Xiao Ming')
stu2 = Student('001', 'floret')

check

  • Object Property - gets the object property value
  • Getattr (object, property name) - get the value of the specified property of the object. If the property does not exist, an error will be reported
  • Getattr (object, property name, default value) - gets the value of the specified property of the object. If the property does not exist, the default value is returned
print(stu1.name)  # Xiao Ming
print(getattr(stu1, 'name'))  # Xiao Ming
# print(getattr(stu1, 'gender'))  # AttributeError: 'Student' object has no attribute 'gender'
print(getattr(stu1, 'gender', 'male'))  # male

Addition and modification

  • Object Attribute = value - when the attribute exists, modify the value of the attribute, and add the attribute when the attribute does not exist;
  • Setattr (object, attribute, name, value)
print(stu1)  # <'stu_ ID ':'000','name ':'xiaoming','age ': 18 >
stu1.gender = 'female'
setattr(stu1, 'age', 100)  # The modified age is 100
print(stu1)  # <'stu_ ID ':'000', 'name':'xiaoming ',' age ': 100,' gender ':'female' >

Delete

  • del object Property - deletes the specified property of the specified object
  • Delattr (object, attribute name) - deletes the specified attribute of the specified object
print(stu1)  # <'stu_ ID ':'000', 'name':'xiaoming ',' age ': 100,' gender ':'female' >
# del stu1.age
delattr(stu1, 'age')
print(stu1)  # <'stu_ ID ':'000','name ':'xiaoming','gender ':'female' >

Built in properties

__slots__

  • __ slots__ The value of the attribute is the object attribute that the object of the current class can have at most;
  • If it is empty, the object of this class cannot have object properties;
  • If this class is set__ slots__ Property, then it can no longer be used__ dict__ Attributes;
class A:
    """
    Class description document
    """
    # __ slots__ The value of the property is the object property that the object of the current class can have at most
    # If it is empty, the object of this class cannot have object properties
    # If this class is set__ slots__ Property, then it can no longer be used__ dict__ attribute
    __slots__ = ('x', 'y', 'z')

    def __init__(self, x=10, y=10):
        self.x = x
        self.y = y


a = A()
# a.m = 300  # TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'

__doc__

  • Class description document
# print(int.__doc__)
print(A.__doc__)  # Class description document

__module__

  • Gets the module where the class is located
print(int.__module__)  # builtins
print(A.__module__)  # __ main__  Current module

__class__

  • Get the type, function and type() of the object
a = A()
print(a.__class__)  # <class '__main__.A'>
print(type(a))  # <class '__main__.A'>

__dict__

  • Get all class (object) properties and corresponding values of the class (object) and return them in the form of a dictionary
print(a.__dict__)  # {'x': 10, 'y': 10}

__name__

  • Get the name of the class (class property)
print(A.__name__)  # 'A'

__ base__ And__ bases__

  • __ base__ - Gets the parent class of the current class

  • __ bases__ - Gets the parent class of the current class

print(A.__base__)  # <class 'object'>
print(A.__bases__)  # (<class 'object'>,)

Operator overloading

introduction

print(10 + 29)
print('abc' + '34')
print([10, 34] + [235, 0, 'abc'])

# 10 + 29 == 10.__add__(29)  # +No. essentially calls the magic method in the int class
# 'abc' + '34' == 'abc'__add__('34')  # +No. essentially calls the magic method in the str class

heavy load

  • Each operator in Python corresponds to a fixed magic method. The data of that type supports the corresponding operator for the corresponding magic method implemented in that type;

  • Whether a data in Python supports an operator depends on whether the magic method corresponding to the operator is defined in this class;

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __add__(self, other):  # Make the object support the + sign
        return [stu1, stu2]

    def __gt__(self, other):
        return self.age > other.age

    def __repr__(self):
        return f'<{str(self.__dict__)[1:-1]}>'


stu1 = Student('Xiao Ming', 18)
stu2 = Student('floret', 20)

a = stu1 + stu2  # a = stu1.__add__(stu2)
print(a)  # [<'name ':'xiaoming','age ': 18 >, <'name':'xiaohua ','age': 20 >]
# Find the oldest student max high-order usage
print(max(a, key=lambda x: x.age))
# Custom magic method to realize the function of operator >
print(stu1 > stu2)  # False

inherit

  • Inheritance is to let subclasses directly own the properties and methods of the parent class

    • Subclass - successor
    • Parent class - inheritee, also known as superclass
  • grammar

    class Class name(Parent class, Parent class 2, Parent class 3, ...):
        Documentation
        Class content
    
  • Note: if no inheritance relationship is written when defining a class, this class inherits the base class object by default

    • Class name: = = class name (object):

Add new properties and methods to subclasses

Add methods and add class properties

  • Define new class properties and methods directly in subclasses

Add object properties

  • After adding an object attribute to a subclass, you cannot directly call the object attribute of the parent class;

  • Use super () in subclass object properties__ init__ () to call the object attribute of the parent class;

class Person:
    num = 99

    def __init__(self):
        self.name = 'Zhang San'
        self.age = 20
        self.gender = 'male'

    def eat(self, food):
        print(f'Eating{food}')

    @staticmethod
    def func1():
        print('Static method')


class Student(Person):
    x = 'student'

    def __init__(self):
        # Calls the method of the parent class of the current class
        super().__init__()
        self.study_id = '0001'
        self.subject = 'Python'

    def study(self):
        print('make progress every day')

    @classmethod
    def func2(cls):
        print('Class method')


# Inherited syntax
stu = Student()
print(stu.name, stu.age, stu.gender)  # Zhang San, 20 male
stu.eat('steamed stuffed bun')  # Zhang San is eating steamed stuffed buns
stu.func1()  # Static method
print(stu.num)  # 99

Inheritance details

Subclasses and superclasses have the same methods

class A:
    def func1(self):
        print('A of func1')


class B(A):
    def func1(self):
        print('B of func1')


B().func1()  # func1 of B
A().func1()  # func1 of A

super usage

  • Super (class, object) Method () - calls the specified method of the parent class of the specified class
  • Note: () in parentheses, the object must be the object of the class in parentheses
class A:
    def func1(self):
        print('A of func1')


class B(A):
    def func2(self):
        super(B, self).func1()  # func1 of A
        print('B of func2')  # func2 of B


B().func2()  # Func1 of A func2 of B

Multiple inheritance

  • A subclass can only inherit the object properties of the first parent class, and both method and class properties can inherit
class A:
    num = 1

    def __init__(self):
        self.x = 2
        self.y = 3

    def func_A(self):
        print('Object method A')


class B:
    mess = 'a'

    def __init__(self):
        self.m = 'b'
        self.n = 'c'

    def func_B(self):
        print('Object method B')


class C(A, B):
    pass


# Class properties
c = C()
print(c.num, c.mess)  # 1 a
# method
c.func_B()  # Object method B
c.func_A()  # Object method A

# Object properties
print(c.x, c.y)  # 2 3
# print(c.m, c.n)  # AttributeError: 'C' object has no attribute 'm'

Privatization

  • Access permissions (permissions for properties and methods): public, protected, and private

    • Public - can be used outside the class, inside the class, or inherited
    • Protected - cannot be used outside the class, can be used inside the class, or can be inherited
    • Private - can only be used inside a class, cannot be inherited, and cannot be used outside
    • There is only one permission for the content of classes in python: public
  • Private methods in python precede variables and methods with '_'

  • python privatization is a kind of pseudo privatization. Its essence is to add 'class name' before the privatization name when storing data;

  • Protection in python: prefix the name with "" (an underscore)

class A:
    m = 100
    __n = 200

    @staticmethod
    def func1():
        print('Open')

    @staticmethod
    def __func2():
        print('Private')


a = A()
print(A.m)  # 100
a.func1()  # Open
# print(A.n)  # AttributeError: type object 'A' has no attribute 'n'
# a.func2()  # AttributeError: 'A' object has no attribute 'func2'
print(A._A__n)  # 200
a._A__func2()  # Private

Copy

Direct assignment

  • Directly assign the address in the variable to another variable. After the assignment, the two variables point to the same memory area and affect each other

Shallow copy

  • List, slice, list copy(), dictionary copy() etc
  • Copy the original data to generate a new data, and return the address of the new data; If there are sub objects (variable data) in the source data, the sub objects will not be copied;

Deep copy

  • Copy the source data to generate a new data and return the address of the new data. If there are sub objects in the original data, the sub objects will also be copied;
from copy import copy, deepcopy
class Dog:
    def __init__(self, name, gender='mother'):
        self.name = name
        self.gender = gender

    def __repr__(self):
        return str(self.__dict__)


class Person:
    def __init__(self, name, age=18, dog=None):
        self.name = name
        self.age = age
        self.dog = dog

    def __repr__(self):
        return str(self.__dict__)


p1 = Person('Xiao Ming', dog=Dog('floret'))
p2 = p1
p3 = copy(p1)
p4 = deepcopy(p1)
print(f'p1(Source data):{p1}')  # P1 (source data): {name ':' Xiaoming ',' age ': 18,' dog ': {name': 'Xiaohua', 'gender': 'female'}}
print(f'p2(After assignment):{p2}')  # P2 (after assignment): {name ':' Xiaoming ',' age ': 18,' dog ': {name': 'Xiaohua', 'gender': 'female'}}
print(f'p3(Shallow copy):{p3}')  # P3 (light copy): {name ':' Xiaoming ',' age ': 18,' dog ': {name': 'Xiaohua', 'gender': 'female'}}
print(f'p4(Deep copy):{p4}')  # P4 (deep copy): {name ':' Xiaoming ',' age ': 18,' dog ': {name': 'Xiaohua', 'gender': 'female'}}
print('----------------Before and after assignment, copy and deep copy----------------')
p1.dog.name = 'idiot'
print(f'p1(Source data):{p1}')  # P1 (source data): {name ':' Xiao Ming ',' age ': 18,' dog ': {name': 'fool', 'gender': 'parent'}}
print(f'p2(After assignment):{p2}')  # P2 (after assignment): {name ':' Xiao Ming ',' age ': 18,' dog ': {name': 'fool', 'gender': 'parent'}}
print(f'p3(Shallow copy):{p3}')  # P3 (shallow copy): {name ':' Xiao Ming ',' age ': 18,' dog ': {name': 'fool', 'gender': 'parent'}}
print(f'p4(Deep copy):{p4}')  # P4 (deep copy): {name ':' Xiaoming ',' age ': 18,' dog ': {name': 'Xiaohua', 'gender': 'female'}}

memory management

Memory request

  • When defining variables to save data, the system will automatically apply.
  • Definition variables store variable data, and new memory will be applied every time.
  • If the definition variable stores immutable data, you will first check whether the data has been saved. If it has been stored, you will not apply for new memory.

release

  • If the reference count of a data is 0, the data will be automatically released;
  • Reference: the object that holds the data address is the reference of this data;

Keywords: Python

Added by pikymx on Fri, 31 Dec 2021 19:26:53 +0200