[Tutor] class arguments?

Kent Johnson kent37 at tds.net
Thu Jan 22 23:47:46 CET 2009


On Thu, Jan 22, 2009 at 5:18 PM, Kent Johnson <kent37 at tds.net> wrote:
> 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

And to show that these are class attributes:
In [4]: MonoList.item_number
Out[4]: 3

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

Kent


More information about the Tutor mailing list