文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>python中添加方法,等等

python中添加方法,等等

时间:2006-07-09  来源:pipehappy

Functions are descriptors, and their __get__ method is used to bind
them to a particular instance::
     >>> class test(object):
     ...     def __init__(self):
     ...         pass
     ...
     >>> x = test()
     >>> def fun(self):
     ...     print "fun", self
     ...
     >>> x.fun = fun.__get__(x, test)
     >>> x.fun()
     fun <__main__.test object at 0x00E6D730>

Note that calling __get__ returns a bound method, and that method can be
bound to an instance or a class depending on the parameters of __get__::

     >>> fun.__get__(x, None)
     <bound method ?.fun of <__main__.test object at 0x00E74510>>
     >>> fun.__get__(x, test)
     <bound method test.fun of <__main__.test object at 0x00E74510>>
     >>> fun.__get__(None, test)
     <unbound method test.fun>
  Injecting a method into a class, so that even already-created instances
have that method, is trivial:

 >>> class K(object):
...     pass
...
 >>> def fun(self, arg):
...     print "fun"
...     self.frob = arg
...
 >>> o = K()
 >>> K.methc = fun
 >>> o.methc("xyz")
fun
 >>> o.frob
'xyz'
 >>>

Injecting a "private" method into a particular instance is not much more
complicated:

 >>> def own(self, arg):
...    print "own"
...    self.ozz = arg
...
 >>> p = K()
 >>> import types
 >>> p.metho = types.MethodType(own, p)
 >>> p.metho("plugh")
own
 >>> p.ozz
'plugh'
 >>> o = K()
 >>> o.metho("xyzzy")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
AttributeError: 'K' object has no attribute 'metho'
 >>>
 
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载