关于方法中的方法定义问题

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

关于方法中的方法定义问题

vbarter
以下是我从例程中摘录的一个方法:
def NamedTuple(s):
"""Returns a new subclass of tuple with named fields.

>>> Point = NamedTuple('Point x y')
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # works just like the tuple (11, 22)
33
>>> p.x + p.y # fields also accessable by name
33
>>> p # readable __repr__ with name=value style
Point(x=11, y=22)

"""


f = s.split()
typename, field_names = f[0], f[1:]
nargs = len(field_names)

def __new__(cls, *args, **kwds):
if kwds:
try:
args += tuple(kwds[name] for name in field_names[len(args):])
except KeyError, name:
raise TypeError('%s missing required argument: %s' % (typename, name))
if len(args) != nargs:
raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args)))
return tuple.__new__(cls, args)

template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in field_names))
    
def __repr__(self, show=template.__mod__):
return show(self)


m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup)
m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)),
__slots__ = (), # no per-instance dict (so instances are same size as tuples)
__new__ = __new__,
__repr__ = __repr__,
)
m.update((name, property(itemgetter(index))) for index, name in enumerate(field_names))

return type(typename, (tuple,), m)

我对其中几个部分不懂:

1  在方法NamedTuple(s)中定义__new__()和__repar__()是重载么?如果是,重载不需要在类中进行么?
2  __new__()和__repar__()各自在什么时候被调用?
3 有很多的__slots__ ,__new__, __repr__系统变量,这些变量改怎么来了解他们的用途么?


学习ing

_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese
Reply | Threaded
Open this post in threaded view
|

Re: 关于方法中的方法定义问题

yi huang-3
On 1/31/07, 俊杰蔡 <[hidden email]> wrote:
以下是我从例程中摘录的一个方法:
def NamedTuple(s):
"""Returns a new subclass of tuple with named fields.

>>> Point = NamedTuple('Point x y')
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # works just like the tuple (11, 22)
33
>>> p.x + p.y # fields also accessable by name
33
>>> p # readable __repr__ with name=value style
Point(x=11, y=22)

"""


f = s.split()
 
typename, field_names = f[0], f[1:]
 
nargs = len(field_names)
 

def __new__(cls, *args, **kwds):
 
if kwds:
 
try:
 
args += tuple(kwds[name] for name in field_names[len(args):])
 
except KeyError, name:
 
raise TypeError('%s missing required argument: %s' % (typename, name))
 
if len(args) != nargs:
 
raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args)))
 
return tuple.__new__(cls, args)
 

template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in field_names))
 
    
def __repr__(self, show=template.__mod__):
 
return show(self)

 

m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup)
 
m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)),
 
__slots__ = (), # no per-instance dict (so instances are same size as tuples)
 
__new__ = __new__,
 
__repr__ = __repr__,
 
)
 
m.update((name, property(itemgetter(index))) for index, name in enumerate(field_names))
 

return type(typename, (tuple,), m)
 

我对其中几个部分不懂:

1  在方法NamedTuple(s)中定义__new__()和__repar__()是重载么?如果是,重载不需要在类中进行么?
2  __new__()和__repar__()各自在什么时候被调用?
3 有很多的__slots__ ,__new__, __repr__系统变量,这些变量改怎么来了解他们的用途么?


学习ing

_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: <a onclick="return top.js.OpenExtLink(window,event,this)" href="http://python.cn/mailman/listinfo/python-chinese" target="_blank"> http://python.cn/mailman/listinfo/python-chinese
 
注意最后一句:
type(typename, (tuple,), m)
 
这是 metaclass 的范畴了,实际上:
class Temp(tuple):
    a = 1
    def test(self):pass
 
等价于:
def test(self):pass
Temp = type('Temp', (tuple,), {'a':1, 'test':test})
 
 
 

_______________________________________________
python-chinese
Post: send [hidden email]
Subscribe: send subscribe to [hidden email]
Unsubscribe: send unsubscribe to  [hidden email]
Detail Info: http://python.cn/mailman/listinfo/python-chinese