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

區分方法和函數

都是 per object 我們 iterable on() ble 靜態方法 stat

# 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

  

區分方法和函數