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

Ben Finney ben+python at benfinney.id.au
Mon Jun 18 03:29:50 EDT 2018


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.

-- 
 \          “Now Maggie, I’ll be watching you too, in case God is busy |
  `\       creating tornadoes or not existing.” —Homer, _The Simpsons_ |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list