1. 程式人生 > >區分方法和函式

區分方法和函式

# 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