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

    # 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
    

      

  • 相关阅读:
    【Linux】PS命令
    【Linux】多进程与多线程之间的区别
    【杂项】XML Schema和DTD的区别
    推荐一组强大的Collection类
    关于Decorator模式我的理解
    菜鸟白话设计模式系列
    PowerCollections研究: 第1弹竟就发现不少问题
    [白话设计模式] Singleton
    PowerCollection研究:第2枪小谈RemoveALL算法
    yield 关键字
  • 原文地址:https://www.cnblogs.com/work14/p/10187506.html
Copyright © 2011-2022 走看看