[Tutor] class arguments?

Kent Johnson kent37 at tds.net
Thu Jan 22 23:18:54 CET 2009


On Thu, Jan 22, 2009 at 4:51 PM, spir <denis.spir at free.fr> wrote:
> Hello,
>
> is there a way to give arguments to a class definition? Eg
>
> class MonoList(list, typ, number):
>        item_type = typ
>        item_number = number

Use the type() function (which is the constructor for the type 'type')
to dynamically create classes (i.e. types), e.g.

In [1]: typ = int

In [2]: number = 3

In [3]: MonoList = type("MonoList", (list,), dict(item_type=typ,
item_number=number))

In [4]: ml = MonoList()

In [5]: ml.item_type
Out[5]: <type 'int'>

In [6]: ml.item_number
Out[6]: 3

In [7]: isinstance(ml, list)
Out[7]: True

http://docs.python.org/library/functions.html#type

Kent


More information about the Tutor mailing list