Python 中函数和方法

时间:2023-03-09 20:38:44
Python 中函数和方法

函数与方法

class Foo(object):
    def __init__(self):
        self.name = 'lcg'

    def func(self):
        print(self.name)

obj = Foo()
print(obj.func)  # <bound method Foo.func of <__main__.Foo object at 0x000001ABC0F15F98>>

print(Foo.func)  # <function Foo.func at 0x000001ABC1F45BF8>

# ------------------------FunctionType, MethodType------------#

from types import FunctionType, MethodType

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

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

# ------------------------------------------------------------#
obj = Foo()
Foo.func(obj)  # lcg

obj = Foo()
obj.func()  # lcg

"""
注意:
    方法,无需传入self参数
    函数,必须手动传入self参数
"""