day18 - advanced object oriented
1. Add, delete, modify and query object attributes
(1) Query - get attribute value
- Object Property - gets the value of the specified property of the object. If the property does not exist, an error will be reported
- 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, attribute name, default value) - gets the value of the specified attribute of the object. If the attribute does not exist, the default value is returned
print(stu1.name) print(getattr(stu1, 'name')) print(getattr(stu1, 'name', 'anonymous person'))
(2) Addition and modification
- Object Attribute = value - modify the value of the attribute when the attribute exists, and add the attribute when the attribute does not exist
- Getattr (object, attribute name, value) - modify the value of the attribute when it exists, and add the attribute when it does not exist
stu1.name = 'Zhang San' print(stu1) # < {'name': 'Zhang San', 'age': 18, 'study_id': '000'} > stu1.gender = 'female' print(stu1) # < {'name': 'Zhang San', 'age': 18, 'study_id': '000', 'gender': 'female'} > print(stu1.gender) # female setattr(stu1, 'age', 30) print(stu1.age) # 30 setattr(stu1, 'score', 100) print(stu1) # < {'name': 'Zhang San', 'age': 30, 'study_id': '000', 'gender': 'female', 'score': 100} > print(stu1.score) # 100
(3) Delete
- del object Property - deletes the specified property of the specified object
- Delattr (object, attribute name) - deletes the specified attribute of the specified object
del stu1.age print(stu1) # < {'name': 'Zhang San', 'study_id': '000', 'gender': 'female', 'score': 100} > delattr(stu1, 'study_id') print(stu1)
class A: # __ 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 an object attribute # Note: if you set__ slots__, Then the object of this class can no longer be used__ dict__ attribute __slots__ = ('x', 'y', 'z') def __init__(self): self.x = 10 a = A() a.y = 100 a.z = 200 # a.m = 300
2. Built in properties
class A: """Or is the computer""" pass
(1) doc - description document of the class
print(int.__doc__) print(int(10).bit_length())
(2) module - gets the module where the class is located
print(int.__module__) print(A.__module__)
(3) class - gets the type, function, and type() of the object
a =A() print(a.__class__) print(type(a))
(4)
- dict - get all class properties and corresponding values of the class and return them in the form of a dictionary
- dict - get all the object properties and corresponding values of the object and return them in the form of a dictionary (object properties)
print(a.__dict__)
(5) name - get the name of the class (class attribute)
print(A.__name__) # 'A'
- Yes? Type of data
print(f'yes{a.__class__.__name__}Type of')
(6)
- base - gets the parent class of the current class
- bases - gets the parent of the current class
print(A.__base__) # < class' object '> base class print(A.__bases__) # <class 'object'>
3. Operator overloading
from copy import copy print(10 + 29) print('abc' + '34') print([10, 34] + [239, 0, 'abc']) print(10 - 9) print({23, 89} - {23}) # 10 + 29 == 10.__add__(29) # 'abc' + '34' == 'abc'.__add__('34')
(1) Operators in Python
- Each operator in python corresponds to a fixed magic method. The corresponding magic method is implemented in which type, and the corresponding operator is supported in which type of data
- 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 # self + other def __add__(self, other): return self.age + other.age # self * other def __mul__(self, other): return [copy(self) for _ in range(other)] # self > other def __gt__(self, other): return self.age > other.age def __repr__(self): return f'<{str(self.__dict__)[1:-1]}, id: {id(self)}>' # return str(self.__dict__)
stu1 = Student('Xiao Ming', 18) stu2 = Student('floret', 20) a = stu1 + stu2 # a = stu1.__add__(stu2) print(a) print(stu1 * 4) # print(stu1 in stu2) stu_list = [stu1, stu2, Student('Zhang San', 12)] print(stu_list) # print(max(stu_list, key=lambda item: item.age)) print(max(stu_list))
4. Succession
(1) 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
(2) Usage of inheritance
-
Class name (parent class):
Documentation
Class content
-
Class class name (parent class 1, parent class 2,...):
Documentation
Class content
-
Note: if no inheritance relationship is written when defining a class, this class inherits the base class object by default
-
Class class name: = = class class name (object)
(3) Add new properties and methods
- Add methods and add class properties: define new class properties and methods directly in subclasses
- Add object properties
class Person: num = 61 def __init__(self,): self.name = 'Zhang San' self.age = 30 self.gender = 'male' def eat(self, food): print(f'{self.name}Eating{food}') @staticmethod def func1(): print('Static method') class Student(Person): x = 'student' def __init__(self): # Calling the parent class of the current class__ init__ method super().__init__() self.study_id = '0001' self.subject = 'python' def study(self): print('study hard and make progress every day!') @classmethod def func2(cls): print('Students' class methods') stu = Student() print(stu.name, stu.age, stu.gender) stu.eat('steamed stuffed bun') print(Student.num) Student.func1() print(Student.x) stu.study() Student.func2() print(stu.study_id, stu.subject) class A: def __init__(self, x, y): self.x = x self.y = y class B(A): def __init__(self, m, n, x=10, y=20): super().__init__(x, y) self.m = m self.n = n a = A(200, 300) b = B(1, 2) print(b.x, b.y) # b.x = 3 # b.y = 4
5. Succession details
(1) Subclasses and superclasses have the same method (override)
class A: def func1(self): print('A of func1') class B(A): def func1(self): print('B of func1') B().func1() A().func1()
(2) super usage
- Super (class, object) Method () - calls the specified method of the parent class of the specified class
- Note: the object in () must be the object of the class in ()
class A: def func1(self): print('A of func1') class B(A): def func2(self): super(B, self).func1() print('B of func2') B().func2() class A: def func1(self): print('A of func1') def func2(self): print('A of func2') class B(A): def func1(self): print('B of func1') class C: def func1(self): print('C of func1') class D(C): def func1(self): super(B, B()).func2() print('D of func1') d = D() d.func1()
(3) Multi inheritance: a subclass can only inherit the object properties of the first parent class (both method and class properties can be inherited)
class AA: num = 100 def __init__(self): self.x = 100 self.y = 200 def func1(self): print('Object method AA') class BB: message = 'Hello' def __init__(self): self.m = 100 self.n = 200 def func2(self): print('Object method BB') class CC(AA, BB): pass c = CC() print(CC.num, CC.message) c.func1() c.func2() print(c.x, c.y) # print(c.m, c.n) # AttributeError: 'CC' object has no attribute 'm'
(4) 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 - only the inside of the class can be used, cannot be inherited, and cannot be used externally
- There is only one permission for the content of classes in python: public
- Privatization of python: to make properties and methods private, you just need to prefix the name__ (but can't end with _)
- The essence of python privatization: when storing data, add '' before the privatization name_ Class name '
- Protection in python: add before the name_
class A: m = 100 __n = 200 @staticmethod def func1(): print(A.m, A.__n) A.__func2() @staticmethod def __func2(): print('Private method') print(A.m) A.func1() # print(A.__n) # A.__func2() print(A._A__n)
- python hammer
6. Copy
from copy import copy, deepcopy
(1) Copy
-
Direct assignment: directly assign the address in the variable to another variable. After assignment, the two variables point to the same memory area and affect each other
-
Shallow copy: list slice, list copy(), dictionary, copy(), etc. are all shallow copies
: copy the original data to generate a new data, and return the address of the salary reduction data; If there are child objects (variable data) in the original data, the child objects will not be copied
-
Deep copy: deep copy
: copy the original data to generate a new data. Return the address of the new data. If there are sub objects in the original data, the sub objects will also be copied
class Dog: def __init__(self, name, gender='common'): 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('Caicai')) p2 = p1 p3 = copy(p1) p4 = deepcopy(p1) print(f'p1:{p1}, id:{id(p1)}') print(f'p2:{p2}, id:{id(p2)}') print(f'p3:{p3}, id:{id(p3)}') print(f'p4:{p4}, id:{id(p4)}') print('-------------------------------------------------') p1.name = 'floret' p1.dog.name = 'chinese rhubarb' print(f'p1:{p1}, id:{id(p1)}') print(f'p2:{p2}, id:{id(p2)}') print(f'p3:{p3}, id:{id(p3)}') print(f'p4:{p4}, id:{id(p4)}')
(2) Memory management
-
Memory application: when defining variables to save data, the system will apply automatically; If the defined variable is variable data when it is saved; New content will be applied every time. If it is immutable data, the data will be checked
-
Release: if the reference count (number of references) 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