Is it possible to call a class but without a new instance created?
Vincent Vande Vyvre
vincent.vande.vyvre at telenet.be
Mon Jun 18 03:17:41 EDT 2018
Le 18/06/18 à 06:48, Jach Fong a écrit :
> 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
>
Hi,
What you try to do is called a /singleton./
A classic example :
class Foo:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Foo, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, ...):
...
Vincent
Send at Mon, 18 Jun 2018 09:17:21 +0200
More information about the Python-list
mailing list