Simple questions on use of objects (probably faq)
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Thu Mar 9 07:13:17 EST 2006
On Thu, 09 Mar 2006 11:54:11 +0100, Brian Elmegaard wrote:
>> What is "going wrong" exactly ?
>
> def _add_instance(cls, instance):
> _add_instance=classmethod(_add_instance)
> cls._instances.append(instance)
>
> gives me:
> d:/DTU/80494 $ python.exe ooo.py
> Traceback (most recent call last):
> File "ooo.py", line 36, in ?
> Foo(value)
> File "ooo.py", line 6, in __init__
> self._add_instance(self)
> File "ooo.py", line 9, in _add_instance
> _add_instance=classmethod(_add_instance)
> UnboundLocalError: local variable '_add_instance' referenced before assignment
This isn't a bug in version 2.3. It is a bug in your code. Follow the
code at runtime when you call the method:
Calling x._add_instance(foo) calls the _add_instance method with arguments
x.__class__ and foo. The first instruction that gets executed is:
_add_instance=classmethod(_add_instance)
but _add_instance doesn't exist inside the method's local scope, so you
get an UnboundLocalError exception.
What you probably think you want is something like this:
class Foo:
_instances = []
def _add_instance(cls, instance):
cls._instances.append(instance)
_add_instances = classmethod(_add_instances)
I say "think you want" because I don't know what problem you are trying to
solve with this messy, self-referential, piece of code. If you could
explain what your goal is, there is probably a better way of reaching it.
--
Steven.
More information about the Python-list
mailing list