Jach Fong <jf...@ms4.hinet.net> writes: > I also make a test of my own and it fails too. > > >>> class A: > ... objs = [] > ... def __init__(self, exists=False): > ... if exists: self = self.objs[0]
The function parameters (bound here to the names ‘self’, ‘exists’) are in the local function scope. After the function ends, the scope of those names ends; those name bindings no longer affect anything. So, changing what ‘self’ refers to has no effect on the A instance that exists. In other words: Creating the instance is the responsibility of the constructor method (a class method named ‘__new__’), and that instance is what gets passed to the instance initialiser (an instance method named ‘__init__’). The initialiser has no control over what instance gets passed in, and no control over that same instance being returned from the constructor. > What I expect is that id(a0) and id(a1) has the same value. They > should points to the same object. You can't get that effect from within the instance initialiser. What you need to do is change the class constructor (named ‘__new__’), and that's a more advanced topic I leave you to research on your own. -- \ “Now Maggie, I’ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.” —Homer, _The Simpsons_ | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list