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

Jach Fong jfong at ms4.hinet.net
Mon Jun 18 00:48:23 EDT 2018


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.


Best Regards,
Jach Fong




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




More information about the Python-list mailing list