zoukankan      html  css  js  c++  java
  • 区分方法和函数

    在类中:
    实例方法
    如果是类名.方法 函数
    如果是对象.方法 方法
    类方法: 都是方法
    静态方法: 都是函数

    from types import MethodType, FunctionType
    isinstance()
    # def func():
    #     print("我是函数")
    #
    # class Foo:
    #     def chi(self):
    #         print("我是吃")
    #
    # # print(func) # <function func at 0x0000000001D42E18>
    # f = Foo()
    # # f.chi()
    #
    # print(f.chi) # <bound method Foo.chi of <__main__.Foo object at 0x0000000002894A90>>
    #
    # # 野路子: 打印的结果中包含了function. 函数
    # #                         method  .  方法
    #
    
    
    
    
    # 我们的类也是对象.
    # 这个对象: 属性就是类变量
    #          方法就是类方法
    # class Person:
    #     def chi(self):
    #         print("我要吃鱼")
    #
    #     @classmethod
    #     def he(cls):
    #         print("我是类方法")
    #
    #     @staticmethod
    #     def pi():
    #         print("泥溪镇地皮")
    #
    #
    #
    # p = Person()
    # Person.chi(1)  # 不符合面向对象的思维
    
    
    # print(p.chi) # <bound method Person.chi of <__main__.Person object at 0x00000000028C4B70>>
    # print(Person.chi) # <function Person.chi at 0x00000000028989D8>
    
    # 实例方法:
    #   1. 如果使用   对象.实例方法   方法
    #   2. 如果使用     类.实例方法     函数
    
    
    # print(Person.he) # <bound method Person.he of <class '__main__.Person'>>
    # print(p.he) # <bound method Person.he of <class '__main__.Person'>>
    
    
    # 类方法都是 方法
    
    
    
    # print(Person.pi) # <function Person.pi at 0x0000000009E7F488>
    # print(p.pi) # <function Person.pi at 0x0000000009E7F488>
    
    
    # 静态方法都是函数
    
    
    # 记下来
    from types import FunctionType, MethodType # 方法和函数
    from collections import Iterable, Iterator # 迭代器
    
    
    class Person:
        def chi(self): # 实例方法
            print("我要吃鱼")
    
        @classmethod
        def he(cls):
            print("我是类方法")
    
        @staticmethod
        def pi():
            print("泥溪镇地皮")
    
    
    p = Person()
    
    print(isinstance(Person.chi, FunctionType)) # True
    print(isinstance(p.chi, MethodType)) # True
    
    print(isinstance(p.he, MethodType)) # True
    print(isinstance(Person.he, MethodType)) # True
    
    print(isinstance(p.pi, FunctionType)) # True
    print(isinstance(Person.pi, FunctionType)) # True
    

      

  • 相关阅读:
    java算法:树遍历
    java算法:图遍历(深度优先和广度优先)
    Google禁止继续研发开源的"盖亚计划"
    Vc编程调试入门
    访著名Linux内核程序员大鹰
    访著名Linux内核程序员大鹰
    百度玩"精准搜索" 个人隐私保护问题值得商榷
    Google禁止继续研发开源的"盖亚计划"
    加密CMD使电脑溢出也拿不到CMD权限
    百度玩"精准搜索" 个人隐私保护问题值得商榷
  • 原文地址:https://www.cnblogs.com/YangWenYu-6/p/10187627.html
Copyright © 2011-2022 走看看