Differences between revisions 3 and 5 (spanning 2 versions)
Revision 3 as of 2006-04-22 16:33:25
Size: 1259
Editor: HuangYi
Comment:
Revision 5 as of 2009-12-25 07:14:04
Size: 1235
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:
返回::'''[wiki:self/PyIAQ  Python 罕见问题集]''' 返回::'''[[self:PyIAQ|Python 罕见问题集]]'''
Line 6: Line 6:
::-- ["huangyi"] [[[DateTime(2006-04-22T16:26:39Z)]]]
[[TableOfContents]]
::-- [[huangyi]] [<<DateTime(2006-04-22T16:26:39Z)>>]
<<TableOfContents>>
Line 9: Line 9:
::-- ZoomQuiet [[[DateTime(2005-09-06T04:10:30Z)]]]
[[TableOfContents]]
::-- ZoomQuiet [<<DateTime(2005-09-06T04:10:30Z)>>]
<<TableOfContents>>
Line 12: Line 12:
''Q: f(*m)这个技巧确实不错。不知道这个语法是否可以用在方法调用上, 比如 x.f(*y)?'' ''Q: The f(*m) trick is cool. Does the same syntax work with method calls, like x.f(*y)?''

返回::Python 罕见问题集

::-- huangyi [2006-04-22 16:26:39]

::-- ZoomQuiet [2005-09-06 04:10:30]

1. 问:f(*m)这个技巧确实不错。不知道这个语法是否可以用在方法调用上, 比如 x.f(*y)?

Q: The f(*m) trick is cool. Does the same syntax work with method calls, like x.f(*y)?

This question reveals a common misconception. There is no syntax for method calls! There is a syntax for calling a function, and there is a syntax for extracting a field from an object, and there are bound methods. Together these three features conspire to make it look like x.f(y) is a single piece of syntax, when actually it is equivalent to (x.f)(y), which is equivalent to (getattr(x, 'f'))(y). I can see you don't believe me. Look:

   1 class X:
   2     def f(self, y): return 2 * y
   3 
   4 >>> x = X()
   5 >>> x.f
   6 <bound method X.f of <__main__.X instance at 0x009C7DB0>>
   7 >>> y = 21
   8 >>> x.f(y)
   9 42
  10 >>> (x.f)(y)
  11 42
  12 >>> (getattr(x, 'f'))(y)
  13 42
  14 >>> xf = x.f
  15 >>> xf(y)
  16 42
  17 >>> map(x.f, range(5))
  18 [0, 2, 4, 6, 8]

PyIAQ/Q12 (last edited 2009-12-25 07:14:04 by localhost)