On Saturday, March 2, 2013 11:02:14 AM UTC-6, gialloporpora wrote:
> I would like to inherit from the list native class. really
> I expected that was possible to use native list method
> without redefining them, for example the __repr__ method.
>
> [...]
>
> class vector(list):
> def __init__(self, *args):
> self._list = list(args)
> self._index = 0
Here is where you go wrong.
First of all why would you inherit from "list" and then create a new list as
attribute, that seems a bit silly huh? If you want your custom list to
"inherit" all the pre-defined methods of the python list type, then do so.
>>> class MyList(list):
pass
>>> ml = MyList()
>>> dir(ml)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
>>> ml
[]
>>> ml.append('cat')
>>> ml
['cat']
>>> ml.extend(range(5))
>>> ml
['cat', 0, 1, 2, 3, 4]
>>> ml.sort()
>>> ml
[0, 1, 2, 3, 4, 'cat']
>>> isinstance(ml, list)
True
Quacks like a list to me. In this case you did not need to call the superclass
constructor explicitly; for example.
class MyList(list):
def __init__(self):
list.__init__(self)
...is really a waste of time because you will not have any options to pass to
the super.
>>> ml2 = MyList2()
>>> dir(ml2)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
>>> ml2+[10,20,30]
[10, 20, 30]
>>> ml2
[]
>>> ml2.append('salt')
>>> ml2
['salt']
>>> isinstance(ml2, list)
True
If however you wanted to create a custom Tkinter widget, you would then need to
pass the options from the derived class __init__ method into the superclass
__init__ method, like this:
class MyButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self, master, **kw)
mb = MyButton(rootWindow, text='PushMe', command=helloButton)
What are you trying to achieve exactly?
--
http://mail.python.org/mailman/listinfo/python-list