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

Chris Angelico rosuav at gmail.com
Mon Jun 18 03:25:49 EDT 2018


On Mon, Jun 18, 2018 at 2:48 PM, Jach Fong <jfong at ms4.hinet.net> wrote:
> After looking into the \tkiniter\font.py source file, triggered by Jim's
> hint on my previous subject "Why an object changes its "address" between
> adjacent calls?", I get more confused.
>
> Below was quoted from the font.py:
> ------------------------
> def nametofont(name):
>     """Given the name of a tk named font, returns a Font representation.
>     """
>     return Font(name=name, exists=True)
>
> class Font:
>     """Represents a named font.
>     Constructor options are:
>     ...
>     exists -- does a named font by this name already exist?
>        Creates a new named font if False, points to the existing font if
> True.
>     ...
>     """
>
>     def __init__(self, root=None, font=None, name=None, exists=False,
>                  **options):
>         ...
> ----------------------
> From my understanding, the __init__ method was called after the instance
> was created, that's why the __init__ has a self parameter, right? Then,
> how is it possible "...points to the existing font if True"? I didn't
> see any clue in __init__ doing this.
>
> 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]
> ...             else:  self.objs.append(self)
> ...
>>>> a0 = A()
>>>> id(a0)
> 35569968
>>>> a1 = A(exists=True)
>>>> id(a1)
> 35572336
>
> What I expect is that id(a0) and id(a1) has the same value. They should
> points to the same object.

Yes, what you want is possible; but you need a slightly different
method. Assigning to 'self' doesn't do anything - it's not magical,
it's just a parameter. Instead, look into overriding __new__; that's
how, for instance, the int() constructor can return cached objects.

ChrisA



More information about the Python-list mailing list