instance variable weirdness

Felipe Almeida Lessa felipe.lessa at gmail.com
Fri Apr 14 12:31:43 EDT 2006


Em Sex, 2006-04-14 às 13:30 -0300, Felipe Almeida Lessa escreveu:
> To solve your problem, change 
>     def __init__(self, name, collection=[]):
>         BaseClass.__init__(self)
>         self.name = name
>         self.collection = collection # Will reuse the list
> to
>     def __init__(self, name, collection=None):
>         BaseClass.__init__(self)
>         self.name = name
>         if collection is None:
>             collection = [] # Will create a new list on every instance
>         self.collection = collection

Or if None is valid in your context, do:

    __marker = object()
    def __init__(self, name, collection=__marker):
        BaseClass.__init__(self)
        self.name = name
        if collection is __marker:
            collection = [] # Will create a new list on every instance
        self.collection = collection

-- 
Felipe.




More information about the Python-list mailing list