Is it possible to call a class but without a new instance created?

Jach Fong jfong at ms4.hinet.net
Mon Jun 18 19:48:04 EDT 2018


Ben Finney at 2018/6/18 PM 03:29 wrote:
> Jach Fong <jfong at 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.
> 
class B:
     _obj = None
     def __new__(*args, **kwargs):
         if not B._obj:
             B._obj = object.__new__(*args, **kwargs)
         return B._obj

b0 = B()
b1 = B()
assert b0 is b1

Although it passed the first examination, I have no idea if it can
work correctly in the real application:-)

--Jach

---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus




More information about the Python-list mailing list