Python Object-Oriented Advancement

Posted by Lefu on Fri, 17 May 2019 17:14:41 +0200

Object-Oriented Advancement

I. isinstance and issubclass built-in methods

1,isinstance(obj,cls)

Function: Check whether obj is an object of cls class?

2,issubclass(sub, super)

Function: Check whether the sub class is a derivative of the super class?

2. Reflex (introspection)

1. Definition:

The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect and modify its own state or behavior (introspection). The introduction of this concept soon led to the study of application reflexivity in computer science. It is first adopted in the field of programming language design, and has made achievements in Lisp and object-oriented.

2. Reflection in python:

By manipulating object-related properties in the form of strings, everything in python is an object (you can use reflection).

3. Four Functions for Self-reflection

hasattr(obj,name): returns whether the obj object has the properties described by name

(2) getattr(obj,name): Get the properties described by name from the obj object

(3) setattr(obj,name,value): Set an attribute named name to the obj object with the value of the attribute

delattr(obj,name): Delete an attribute named name from an obj object

(5) Examples of application of reflection:

# · Attributes and Methods in Reflective Objects
class Foo:
    static_var = 'Class static variables'

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

    def say_hi(self):
        print('hello,%s' % self.name)

foo_obj = Foo('Yang',66)

# Using hasattr function to detect whether there is an attribute or not
print(hasattr(foo_obj,'name'))
print(hasattr(foo_obj,'say_hi'))


# Getting attributes with getattr
print(getattr(foo_obj,'name'))
func=getattr(foo_obj,'say_hi')
func()
print(getattr(foo_obj,'x','It doesn't exist.')) #Report errors


#Set attr to set properties
setattr(foo_obj,'yo',True)
setattr(foo_obj,'show_name',lambda self:self.name+'yoyoyo')
print(foo_obj.__dict__)
print(foo_obj.show_name(foo_obj))

#Delete attributes with delattr
delattr(foo_obj,'age')
delattr(foo_obj,'show_name')
delattr(foo_obj,'not_exist_func') #If it does not exist, it will report an error.

print(foo_obj.__dict__)

# · Methods and attributes of reflection classes
class Foo(object):
    static_var = "Static attributes of classes"

    def __init__(self):
        self.name = 'Short suffering'

    def func(self):
        return 'I use python'

    @staticmethod
    def bar():
        return 'bar func...'

print(getattr(Foo, 'static_var'))
print(getattr(Foo, 'func'))
print(getattr(Foo, 'bar'))

# · Properties and methods of reflection modules (built-in modules are also possible)
'''
//Program catalogue:
    module_test.py
    index.py

//Current document:
    index.py
'''
import module_test as obj

print(hasattr(obj, 'test'))

print(getattr(obj, 'test'))

# · Reflect functions in your module
import sys

def s1():
    print('s1')

def s2():
    print('s2')

this_module = sys.modules[__name__] # Return to your own module

print(hasattr(this_module, 's1'))
print(getattr(this_module, 's2'))

3. Built-in methods of classes

1,__str__,__repr__

Note: The relationship between built-in class methods and pre-built functions

(2) str_ method

  • The object class implements _str_, and the _str_ method in the object returns the memory address of the object calling the method.
  • % s, str(), print() are all actually executing the built-in method _str__
  • If the custom class overrides the _str_ method, the string must be returned
  • If there is no _str_ method in the class, the _repr_ method in the class will be found first, and if not, the _str in the default object class will be found again.__
  • If the class inherits the customized parent class, then if there is no _str_, it will continue to look for _str_ in the customized parent class, if not, for its own _repr_, and if not, for _repr_ in the customized parent class (repr is the spare of str, but STR is not the spare of repr)

(3) repr_ method

  • The _repr_ method in object class is implemented, and the _repr_ method in object returns the memory address of the object calling this method.
  • % r, repr() are actually executing the built-in method _repr__
  • If the custom class overrides the _repr_ method, the string must be returned
  • If there is no _repr_ method in the class, the _repr in the parent class is found.__

2,__del__

Definition: Destruction method, which automatically triggers execution when an object is released in memory

(2) Note: This method generally does not need to be defined, because Python is a high-level language, programmers do not need to care about memory allocation and release when using, because this work is handed to Python interpreter to perform, so the call of destructor is triggered automatically by interpreter when garbage collection.

(3) If the _del_ method is rewritten, the code in _del_ will be executed first, but the object will eventually be released in memory.

(4) Examples of application:

class Foo:
def __del__(self):
        print('Implemented__del__Content in....')

f1 = Foo()
del f1
print(f1)

>>> Implemented__del__Content in....
>>> Traceback (most recent call last):
      File "D:/practice.py", line 18, in <module>
        print(f1)
    NameError: name 'f1' is not defined

3,__call__

Definition: The execution of the constructor is triggered by the creation object, that is, the object = the class name (); and the execution of the _call_ method is triggered by the object followed by parentheses, that is, the object () or the class ()) ().

(2) Examples of application:

class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        print('call__call__~~~')


obj = Foo()  # Execute _init__
obj()  # Execution of _call__

4,__new__

Definition: The creation of objects in python first implements the new built-in method, or can be understood as the constructor of classes in python

(2) Application examples:

  • Basic example
            class Foo:
                def __init__(self):
                    print('in __init__')
                def __new__(cls, *args, **kwargs):
                    print('in __new__')
                    return object.__new__(Foo)

            f = Foo()

            >>> in __new__
            >>> in __init__
  • Example of singleton pattern: singleton pattern means that all created objects point to the same object, and the modification of any object is actually an operation on the same object.
            class Single:
                __instance = False
                def __init__(self):
                    pass
                def __new__(cls, *args, **kw):
                    if not hasattr(cls, '_instance'):
                        cls._instance = object.__new__(cls)
                    return cls._instance

            s1 = Single()
            s2 = Single()

            print(s1)
            print(s2)

            >>> <__main__.Single object at 0x00000000011B1B38>
            >>> <__main__.Single object at 0x00000000011B1B38>
  • 1
  • 2
  •  

2,__hash__

(1) Examples of application:

            class A:
                def __init__(self):
                    self.a = 1
                    self.b = 2

                def __hash__(self):
                    return hash(str(self.a)+str(self.b))
            a = A()
            print(hash(a))

3,__eq__

(1) Default judgment of whether the memory addresses of two objects are the same

        class A:
            def __init__(self):
                self.a = 1
                self.b = 2

            def __eq__(self,obj):
                if  self.a == obj.a and self.b == obj.b:
                    return True
        a = A()
        b = A()
        print(a == b)

        >>> True

4. item series - The default object class does not include item series methods

①__getitem__

  • Definition: Obtaining attributes in a class in the form of [key]
  • Example
                class Foo:
                    def __init__(self,attr1,attr2):
                        self.attr1 = attr1
                        self.attr2 = attr2
                    def __getitem__(self, item):
                        return self.attr1

                f = Foo('Attribute 1','Attribute 2')
                print(f['atr1'])

②__setitem__

  • Definition: Create class attributes in [key] fashion
  • Example:
                class Foo:
                    def __init__(self,attr1,attr2):
                        self.attr1 = attr1
                        self.attr2 = attr2
                    def __setitem__(self, key, value):
                        return self.__setattr__(key,value)

                f = Foo('Attribute 1','Attribute 2')
                f['atr3'] = 'Attribute 3'
                print(f.__dict__)
                >>> {'attr1': 'Attribute 1', 'atr3': 'Attribute 3', 'attr2': 'Attribute 2'}

③__del__

  • Definition: This method is executed when calling del class. Attribute
  • Example:
                class Foo:
                    def __init__(self,attr1,attr2):
                        self.attr1 = attr1
                        self.attr2 = attr2
                    def __delitem__(self, key):
                        del key

                f = Foo('Attribute 1','Attribute 2')
                del f['attr1']
                print(f.__dict__)

                >>> {'attr2': 'Attribute 2', 'attr1': 'Attribute 1'}

Topics: Attribute Python Programming Lambda