绑定方法和非绑定方法对象

# !/usr/bin/env python
# -*- coding: utf-8 -*-
class C(object): # define class # 定义类
    def foo(self): pass  # define UDM # 定义 UDM 定义用户方法

c=C()  ###instantiation # 实例化
print  C
print type(C)


C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a14.py
<class '__main__.C'>
<type 'type'>


# !/usr/bin/env python
# -*- coding: utf-8 -*-
class C(object): # define class # 定义类
    def foo(self): pass  # define UDM # 定义 UDM 定义用户方法

c=C()  ###instantiation # 实例化
print  C
print type(C)
print type(c) # type of instance # 实例的类别

print C.foo# 非绑定方法的类别
print c.foo



C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a14.py
<class '__main__.C'>
<type 'type'>
<class '__main__.C'>
<unbound method C.foo>
<bound method C.foo of <__main__.C object at 0x02557C30>>

Process finished with exit code 0

表示11.4 中展示了UDM的属性,访问对象本身将会揭示你正在引用一个绑定方法还是非绑定方法。

UDM(用户定义方法)属性,访问对象本身将会揭示你正在引用一个绑定方法还是非绑定方法。

正如你从下面看到的,绑定的方法揭示了方法绑定到哪一个实例。

>>> C.foo  # unbound method object # 非绑定方法对象
<unbound method C.foo>

>> c.foo  # bound method object # 绑定方法对象
<bound method C.foo of <__main__.C object at 0x00B42DD0>



# !/usr/bin/env python
# -*- coding: utf-8 -*-
class C(object): # define class # 定义类
    'aaaaaaaaaaaaaaaaaaaaaaa'
    def foo(self): pass  # define UDM # 定义 UDM 定义用户方法

c=C()  ###instantiation # 实例化
# print  C
# print type(C)
# print type(c) # type of instance # 实例的类别
#
# print C.foo# 非绑定方法的类别
# print c.foo
# print '------------------'
# print c
# print type(c)
print '--------------------'
print c.__doc__
print '--------------------'

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a14.py
--------------------
aaaaaaaaaaaaaaaaaaaaaaa
--------------------

Process finished with exit code 0
udm.__doc__ 文档字符串(与 udm.im_fuc.__doc__相同)


# !/usr/bin/env python
# -*- coding: utf-8 -*-
class C(object): # define class # 定义类
    'aaaaaaaaaaaaaaaaaaaaaaa'
    def foo(self): pass  # define UDM # 定义 UDM 定义用户方法

c=C()  ###instantiation # 实例化
# print  C
# print type(C)
# print type(c) # type of instance # 实例的类别
#
# print C.foo# 非绑定方法的类别
# print c.foo
# print '------------------'
# print c
# print type(c)
print '--------------------'
print C.__name__
print '--------------------'

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a14.py
--------------------
C
--------------------




猜你喜欢

转载自blog.csdn.net/zhaoyangjian724/article/details/80429747