What is a function, what is a method/what can be followed by parentheses?

difference between function and method

  • The function needs to manually pass self, the method does not need to pass
  • If it is a function, call it with the class name
  • If it is a method, use the object to call 

Example

class Foo(object):
    def __init__(self):
        self.name="haiyan"
    def func(self):
        print(self.name)

obj = Foo()
obj.func()
Foo.func(obj)

Judgment function and method instance

from types import FunctionType,MethodType
obj = Foo()
 print (isinstance(obj.func,FunctionType))   # False 
print (isinstance(obj.func,MethodType))    # True #indicates that this is a method

print (isinstance(Foo.func,FunctionType))   # True #Indicates that this is a function. 
print (isinstance(Foo.func,MethodType)   ) #False

What can be followed by parentheses?

  • method
  • function
  • object
  • kind

The above four can be followed by parentheses ()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782860&siteId=291194637