Python Note -- Day 13.Object-oriented-higher order

Keywords: Python Pycharm

19 Object-oriented - higher order

19.1 Built-in Members

class A():
    pass
class C():
    pass
class B(C):
    pass
class Demo(A,B):
    '''
    Here is the documentation for the class
    '''
    name = "XX"
    age = 30
    def sing(self):
        print('the songs rhythm and melody')
    pass

obj = Demo()

# Gets the member to which the class/object belongs
res = Demo.__dict__    # {'__module__': '__main__', 'name': 'XX', 'age': 30, 'sing': <function Demo.sing at 0x00000000021BA1F8>, '__dict__': <attribute '__dict__' of 'Demo' objects>, '__weakref__': <attribute '__weakref__' of 'Demo' objects>, '__doc__': None}
ree = obj.__dict__     # {} The current object has no attributes of its own
obj.music = 'one'
ree = obj.__dict__     # {'music': 'one'}
print(ree)

# Get the document description class/object for the class. u doc_u
res = Demo.__doc__
res = obj.__doc__

# Gets the string of class names
res = Demo.__name__

# Gets the name of the file where the class is located, if it is the current document, displayed as u main_u
res = Demo.__module__

# Gets the parent list bases of the current class
res = Demo.__bases__   # (<class '__main__.A'>, <class '__main__.B'>)
res = Demo.__base__    # Get the first parent of inheritance <class'u main_u.A'>

# Gets the inheritance chain MRO list of the current class 
res = Demo.mro()    # [<class '__main__.Demo'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>]

Classification of 19.2 Methods

19.2.1 Object Method

Features:
1. Method defined in class, with self parameter
2. Method with self can only be invoked with self
3. The method passes in the called object

class Demo():
    # Object Method
    def f1(self):
        print('this is f1')
# Instantiate Object
o = Demo()
o.f1()
# Object methods cannot be invoked directly using classes, unless an object is passed, which is not recommended
Demo.f1('a')

Class 19.2.2 Methods

Features:
1. Methods in classes are decorated with an ornament @classmethod
2. Method has cls parameter
3. Call directly using a class without instantiating the object
4. Pass in the class that calls this method

class Demo():
    # Class method
    @classmethod
    def f2(cls,a):
        print(cls,a)
        print('this is class function f2')
obj = Demo()
Demo.f2('')
obj.f2('')   # Classes are passed in even when called with an object
# <class '__main__.Demo'>
# this is class function f2

19.2.3 Binding Class Method

Features:
1. Method defined in class with no parameters
2. You can only use classes to make calls
3. No objects or classes will be passed in

class Demo():
    # Binding Class Method
    def f3():
        print('this is bind class function f3')

Demo.f3()
# Cannot call with object

19.2.4 Static Method

Features:
1. The methods defined in the class are decorated with the decorator @staticmethod 2. Calls can be made with objects or classes 3. Objects or classes are not passed in

class Demo():
    # Static method
    @staticmethod
    def f4():
        print('this is static function f4')
    @staticmethod
    def f5(a,b):
        print(a,b)
        print('this is static f5')
Demo.f4()
o = Demo()
o.f4()
Demo.f5(3,4)
o.f5(6,7)

19.3 Common Functions

19.3.1 Detect class and object correlation

  • Issubclass (subclass, parent) detects whether a class is a subclass of another class
res = issubclass(B,C)
print(res)
  • Isinstance (object, class) detects whether an object is an instantiation of a specified class or a subclass of a specified class
class A():
    pass
class B(A):
    pass
class C(A):
    pass
class D(B,C):
    pass

a = A()
b = B()
d = D()
res = isinstance(d,A)
print(res)   # True
  • Hasattr (object/class,'member name') detects whether a class/object contains a member with a specified name
class A():
    age = 20
    _one = ''
class B(A):
    pass
class C(A):
    pass
class D(B,C):
    name = ''
    _sex = ''
    __age = 20
    def say(self):
        print('say sth')

a = A()
b = B()
d = D()
res = hasattr(d,'age')  # True
res = hasattr(B,'age')  # True
res = hasattr(d,'say')  # True
res = hasattr(d,'__age')  # Note to False Private Members!
res = hasattr(d,'_sex')  # True
res = hasattr(d,'_one')  # True

19.3.2 Operational class and object correlation

  • Getattr (class/object,'member name') Gets the value of the member of the class/object except for the private member
class A():
    age = 20
    _one = 'two'
class B(A):
    pass
class C(A):
    pass
class D(B,C):
    name = ''
    _sex = ''
    __age = 18
    def say(self):
        print('say sth')

a = A()
b = B()
d = D()
res = getattr(d,'_one')  # two
res = getattr(d,'say')   # <bound method D.say of <__main__.D object at 0x00000000023CF388>>
print(res)
  • Setattr (object/class,'member name','member value') can set the attribute values of the members of the object/class
setattr(d,'name','ll')
print(d.name) 
  • delattr() deletes members of objects/classes as del deletes members of objects directly
print(d.age) # 20
delattr(A,'age')
print(d.age) # error, no attribute
  • dir() Gets a list of all accessible members of the current object
    print(dir(d))

19.4 Magic Method

19.4.1 related magic methods

Method that can be automatically executed without manual invocation

1. uInit_u Initialization Method
Trigger mechanism: Method that triggers immediately when an object is instantiated
Role: Completes a series of initialization operations for the currently created object, such as assigning member properties, invoking methods, opening or creating resources, etc.
Parameters: one self, receives the current object, and the other parameters are defined as required
Return value: None
Notes: None
    
2. uDel_u destructive method
Trigger mechanism: automatically triggers when an object of this type is destroyed
Role: Close or release some of the resources that were opened or created when the object was created
Argument: a self, receives the current object
Return value: None
Notes: None

3. uNew_u Construction Method
Trigger mechanism: When an object is instantiated, it is automatically triggered (before u init_)
Role: Manage the process of creating control objects
Parameters: One cls, accepts the current class, and the other parameters are determined by the parameters of the initialization method
Return value: must return object. u new_u (cls) for object creation. If no return value exists, the result of instantiating the object is None
Notes:
1. uThe parameters of the new_u method and u init_u are identical except for the first parameter
2.Object. u new_u (cls) must be returned for object creation. If there is no return value, the result of instantiating the object is None
Scenario: Single Case Design in Design Mode

class Person():

    # Construction method
    def __new__(cls, *args):
        print('Trigger construction method')
        print(args)
        # If no object is returned in this method (in the following format), the object cannot be created and the following results are returned after the object is instantiated:
        # Trigger construction method
        # ('zhang', 55, 'male')

        return object.__new__(cls)

    # Initialization Method
    def __init__(self,name,age,sex):
        print('Trigger Initialization Method')
        self.name = name
        self.age = age
        self.sex = sex

    # Destructive methods
    def __del__(self):
        print('Trigger Destruction Method')

# Instantiate Object
one = Person('zhang',55,'male')
# Trigger construction method
# ('zhang', 55, 'male')
# Trigger Initialization Method
# Trigger Destruction Method

4.__call__
Trigger mechanism: automatically triggers when an object is called directly as a function
Role: Generally used to summarize the steps of a class or object for easy invocation
Parameter: one self, accepts objects, other as required
Return value: can or can not

5.__len__
Trigger mechanism: automatically triggers when a len function detects the current object
Role: The len function can be used to detect information about a data of the current object
Parameter: a self
Return value: Must be an integer
Important: To get the value of what attribute len wants, just return the length of which attribute in the return value.

class Demo():
    alist = [1,2,3]
    
    # The len function can be used instead of an object and returns a specified integer
    def __len__(self):
        return len(self.alist)
one = Demo()
res = len(one)
print(res)

6.__str__
Trigger mechanism: automatically triggers when an object is manipulated using str or print functions
Role: String returns instead of objects to customize printed information
Parameter: a self
Return value: must be a string type
Consideration: The content return ed in this method is self-determined

class Demo():
    alist = [1,2,3]

    # String information can be returned as str or print instead of an object
    def __str__(self):
        return 'whatever and wherever str'
one = Demo()
res = str(one)
print(res)  # # whatever and wherever str
print(one)  # whatever and wherever str

7.__repr__
Trigger mechanism: automatically triggers when the current object is converted using the repr method
Role: You can set the result of repr function operation object
Parameter: a self
Return value: must be a string type
Important: Normally u repr_ will execute in place of u str_ without this magic method

8.__bool__
Trigger mechanism: automatically triggers when an object is currently converted using the bool function. By default, the object is converted to True
Role: bool type conversion can be done instead of object, any data can be converted
Parameter: a self
Return value: Must be a bool type return value

class Demo():
    alist = [1,2,3]
    def __bool__(self):
        return bool(self.alist)

one = Demo()
res = bool(one)
print(res)

* Differences between str and repr and corresponding magic methods

1. Both STR and repr functions can dedicate other types of values to strings
2. If there is no more obvious difference between the data objects, the results will be the same

1. The STR function converts the object into a more readable form
2. The repr function converts the object into an interpreter read

n = 3398
r1 = str(n)
r2 = repr(n)
print(r1,type(r1))
print(r2,type(r2))
# 3398 <class 'str'>
# 3398 <class 'str'>

n = '398'
r1 = str(n)
r2 = repr(n)
print(r1,type(r1))
print(r2,type(r2))
# 398 <class 'str'>
# '398' <class 'str'>

Posted by badboy1245 on Sun, 10 Oct 2021 10:01:01 -0700