python - determining functions and methods

7.7.1 determined by printing functions (methods) name

def func():
    pass
print(func)  # <function func at 0x00000260A2E690D0>

class A:
    def func(self):
        pass
print(A.func) # <function A.func at 0x0000026E65AE9C80>
obj = A()
print(obj.func)  # <bound method A.func of <__main__.A object at 0x00000230BAD4C9E8>>

7.7.2 verified by module types

  • Method calls the class name of the class, is a function
  • Object class method invocation, is a method
from types import FunctionType
from types import MethodType

def Foo():
    pass

class A:
    def func(self):
        pass
    
obj = A()

print(isinstance(Foo,FunctionType)) # True
print(isinstance(A.func,FunctionType)) # True
print(isinstance(A.func,MethodType) # False
print(isinstance(obj.func,FunctionType)) # False
print(isinstance(obj.func,MethodType)) # True     

7.7.3 Static method is a function

  • Class name and the object is a function call
  • Class methods: class and object method calls are
from types import FunctionType
from types import MethodType

class A:
    
    def func(self):
        pass
    
    @classmethod
    def func1(self):
        pass
    
    @staticmethod
    def func2(self):
        pass
obj = A()

# 静态方法其实是函数
print(isinstance(A.func2,FunctionType))  # True
print(isinstance(obj.func2,FunctionType))  # True

7.7.4 The difference between the function and method (first two focus)

  • Function: explicit parameter passing are all (manual parameter passing)

  • Method: recessive transmission parameters (automatic transmission parameters - Method class object call automatically object to the self, class methods)

    Function has nothing to do with the object

    The method of operating data inside the class

    The method associated with an object is, for example: a method of string s.strip ()

    The only way in Java, C C ++ function only depends on is in class

Guess you like

Origin www.cnblogs.com/Agoni-7/p/11202757.html