Python reflection and built-in method (Method A double)

Python reflection and built-in method (Method A double)

A reflective

  1. What is the reflection

    The concept is reflected by Smith in 1982 first proposed, mainly refers to the program can access, the ability to detect and modify its own state or behavior (introspection). It puts forward the concept quickly led to research on the application of computer science reflective. It was first used in the field of programming language design, and has made achievements in Lisp and object-oriented aspects.

  2. Python reflective object-oriented

    Properties related to the object operated by a string. Everything is objects in Python (you can use reflection)

    Four function can be achieved self-examination:

    1. hasattr (): comprising detecting whether a property is

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          def func(self):
              pass
      
      # 检测是否含有某属性
      print(hasattr(Foo, "func"))       # True
      f = Foo("dogfa", 18)
      print(hasattr(f, "name"))     # True
      print(hasattr(f, "gender"))       # False
    2. getattr (): Gets property

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          def func(self):
              pass
      
          @staticmethod
          def staticfunc():
              print("嘿嘿嘿")
      
      # 获取属性
      f = getattr(Foo, "staticfunc")
      print(f)  # <function Foo.staticfunc at 0x0000028DD8EB9D08>
      f()           # 嘿嘿嘿
      
      # 如果要获取的属性不存在那么就会报错
      f2 = getattr(Foo, "func1")    # AttributeError: type object 'Foo' has no attribute 'func1'
    3. setattr (): Set Properties

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          def func(self):
              pass
      
          @staticmethod
          def staticfunc():
              print("嘿嘿嘿")
      
      
      f = Foo("dogfa", 18)
      print(f.__dict__)     # {'name': 'dogfa', 'age': 18}
      setattr(f, "name", f.name + "sb")
      print(f.__dict__)     # {'name': 'dogfa_sb', 'age': 18}
    4. defattr (): Delete property

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          def func(self):
              pass
      
          @staticmethod
          def staticfunc():
              print("嘿嘿嘿")
      
      f = Foo("dogfa", 18)
      print(f.__dict__)     # {'name': 'dogfa', 'age': 18}
      delattr(f, "name")
      print(f.__dict__)     # {'age': 18}
      
      # delattr(f, "gender")    # 删除不存在的属性时会报错
  3. Using reflection scenes

    1. Reflection of the object
    2. Reflection of the class
    3. Reflecting the other modules
    4. Reflected current module

Second, the built-in method

  1. Difference function and method

    We first look for the difference between functions and methods prior to said method in Python.

    # 通过导入types模块来验证
    from types import FunctionType, MethodType
    
    def func():
        pass
    
    class A:
        def func(self):
            pass
    
        @staticmethod
        def func2():
            pass
    
    obj = A()
    
    # FunctionType:函数    MethodType:方法
    print(isinstance(func, FunctionType))        # True
    print(isinstance(A.func, FunctionType))      # True
    print(isinstance(obj.func, FunctionType))    # False
    print(isinstance(obj.func, MethodType))      # True
    print(isinstance(A.func2, FunctionType)) # True
    print(isinstance(obj.func2, FunctionType))   # True
    
    
    
    # 通过打印函数(方法)名验证
    from types import FunctionType, MethodType
    def func():
        pass
    
    class A:
        def func(self):
            pass
    
        @staticmethod
        def func2():
            pass
    
    obj = A()
    
    print(func)      # <function func at 0x000002013BC32E18>
    print(A.func)    # <function A.func at 0x000002013BF6A598>
    print(obj.func)  # <bound method A.func of <__main__.A object at 0x000002013BDF7DD8>>

    to sum up:

    (1) function is explicitly pass data. If we want to indicate as len () function to pass some data to be processed.

    (2) function has nothing to do with the object.

    Data (3) method is implicitly transmitted.

    (4) The method of operating data of the internal classes.

    (5) method is associated with the object. As with when we strip () method is invoked through the object str, we have such a string s, then s.strip () called with. Yes, strip () method belongs to the object str.

    (6) static method is a function

  2. Built-in method (Method A double)

    Definition: The Double Down is a special method, his method is of special significance interpreter provided by the method name plus cool underscore double underlined name __ __ method, the method is mainly two-under-source Python programmers, we Do not try to double down method under development, but further research methods double, more beneficial to us to read the source code.

    Call: double under different methods have different trigger modes, like the same organs triggered when Tomb, unknowingly triggered a two-under method, for example: __ init__

    1. item series

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
          def __getitem__(self, item):
              print("执行obj['key']时会执行我")
              return getattr(self, item)
      
          def __setitem__(self, key, value):
              print("执行obj['key'] = value 时会执行我")
              setattr(self, key, value)
      
          def __delitem__(self, key):
              print("执行del['key']时会执行我")
              delattr(self,  key)
      
      obj = Foo("oldwang", 20)
      print(obj["name"])
      # 执行obj['key']时会执行我
      # oldwang
      
      obj["name"] = "oldniu"
      print(obj["name"])
      # 执行obj['key'] = value 时会执行我
      # 执行obj['key']时会执行我
      # oldniu
      
      print(obj.__dict__)
      del obj["name"]
      print(obj.__dict__)
      # {'name': 'oldniu', 'age': 20}
      # 执行del['key']时会执行我
      # {'age': 20}
    2. __of the__

      Destructor, when the object is released in the memory, automatically trigger the execution.

      Note: This method is generally no need to define, because Python is a high-level language, programmers used without concern allocate and free memory, because this work is to the Python interpreter to execute, so call the destructor is It triggered automatically performed at the time garbage collector by an interpreter.

      class FileHandle:
          def __init__(self, file_path):
              self.f = open(file_path, mode="r", encoding="utf-8")
      
          def read(self):
              return self.f.read(1024)
      
          def __del__(self):
              # 在程序执行完时释放文件句柄
              self.f.close()
      
      f = FileHandle("file/userinfo")
      print(f.read())
    3. __new__

      # 单例类
      class Single:
          __isinstance = None
      
          def __new__(cls, *args, **kwargs):
              if not cls.__isinstance:
                  cls.__isinstance = object.__new__(cls)
                  return cls.__isinstance
              return cls.__isinstance
      
      one = Single()
      two = Single()
      print(one is two) # True
    4. __call__

      Brackets behind the object, trigger the execution.

      Note: the constructor is executed by the object triggers created, namely: class name = Object (); For the call performed by the method of the object triggers the brackets, namely: Object () or class () ()

      class Foo:
          def __call__(self, *args, **kwargs):
              print("执行__call__")
      
      f = Foo()
      f()           # 执行__call__
      
      # 还可以这样写
      Foo()()
    5. __len__

      class Foo:
          def __init__(self, name, age):
              self.name = name
              self.age =age
      
          def __len__(self):
              return len(self.__dict__)
      
      f = Foo("dogfa", 18)
      print(len(f)) # 2
    6. __hash__

      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))
    7. __eq__

      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

Third, other

# 有一个员工类,1000个员工对象,对象属性有姓名,性别,年龄,部门,
# 按姓名,性别对1000个对象去重
class Employee:
    def __init__(self, name, age, gender, department):
        self.name = name
        self.age = age
        self.gender = gender
        self.department = department
        
    def __hash__(self):
        return hash("{0}{1}".format(self.name, self.gender))
        
    def __eq__(self, other):
        if self.name == other.name and self.gender == other.gender:
            return True
            
employee_list = []

for i in range(250):
    employee_list.append(Employee("dogfa", i, "male", "python" + str(i)))
    
for i in range(250):
    employee_list.append(Employee("djb", i, "female", "php" + str(i)))
    
for i in range(250):
    employee_list.append(Employee("oldniu", i, "male", "java" + str(i)))
    
for i in range(250):
    employee_list.append(Employee("cdj", i, "female", "go" + str(i)))
    
for employee_obj in set(employee_list):
    print(employee_obj.__dict__)

Guess you like

Origin www.cnblogs.com/wangyueping/p/11111899.html