zoukankan      html  css  js  c++  java
  • python3中如何区分一个函数和方法

    一般情况下,单独写一个def func():表示一个函数,如果写在类里面是一个方法。但是不完全准确。

    class Foo(object):
        def fetch(self):
            pass
    
    print(Foo.fetch)   # 打印结果<function Foo.fetch at 0x000001FF37B7CF28>表示函数
    # 如果没经实例化,直接调用Foo.fetch()括号里要self参数,并且self要提前定义
    obj = Foo()
    print(obj.fetch)  # 打印结果<bound method Foo.fetch of <__main__.Foo object at 0x000001FF37A0D208>>表示方法
    from types import MethodType,FunctionType
    
    class Foo(object):
        def fetch(self):
            pass
    
    
    print(isinstance(Foo.fetch,MethodType))    # False
    print(isinstance(Foo.fetch,FunctionType))  # True
    
    obj = Foo()
    print(isinstance(obj.fetch,MethodType))    # True
    print(isinstance(obj.fetch,FunctionType))  # False
    
    # MethodType方法类型
    # FunctionType函数类型
  • 相关阅读:
    CAP分布式
    专职DBA-MySQL数据库开篇
    os.sep
    DocStrings
    Python如何获取脚本的参数
    LVM基础命令
    VoAndEntityTrans
    短信倒计时
    springboot在eclipse上搭建项目一(无页面)
    springboot问题
  • 原文地址:https://www.cnblogs.com/aaronthon/p/9439477.html
Copyright © 2011-2022 走看看