Singleton Design Pattern | Python Example

แชร์
ฝัง
  • เผยแพร่เมื่อ 11 ม.ค. 2025

ความคิดเห็น • 55

  • @antoniopena1183
    @antoniopena1183 2 ปีที่แล้ว +6

    Dont know why this video has not more views. It is extremely straightforward, informative and clear.

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      Thank you Antonio, I'm very glad to hear you enjoyed the video! :-D

  • @roadtoenlightenment-wu2te
    @roadtoenlightenment-wu2te ปีที่แล้ว +1

    Best explanation I've seen so far regarding Singleton Design in Python. Thanks so much!

  • @ankitpurshottam3442
    @ankitpurshottam3442 3 ปีที่แล้ว +2

    I have been studying this singleton pattern from last 3 days on the internet but none of them was explaining this that way.I must say this is the best way the singleton is explained on the internet kindly upload more design pattern. From india❤️

    • @PortfolioCourses
      @PortfolioCourses  3 ปีที่แล้ว +1

      Thank you so much for this feedback, that's so awesome to hear this was helpful for you. 🙂 I am hoping to upload more design pattern videos in the future.

  • @Samoloh
    @Samoloh 2 ปีที่แล้ว +1

    I jumped from video to video trying to find one that explained clearly and finally, yours explained it clearly thanks!!!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      That's awesome Samuel, I'm so glad to hear that! :-)

  • @sdmagic
    @sdmagic 9 หลายเดือนก่อน

    That was stellar! I've been trying to implement a configuration class that reads a yaml file ONCE per application run without success. You provided all the missing pieces in an extremely easy to understand way! (liked and subscribed) 👍

  • @kifeyabediru9241
    @kifeyabediru9241 3 ปีที่แล้ว +1

    I have to admit, you real good explainer, you go on details. You know your what you know and there is no doubt about it. I wish you have all Python course module by module. Thanks so much.

    • @PortfolioCourses
      @PortfolioCourses  3 ปีที่แล้ว

      Thank you! One day I am hoping to have a full Python course + design patterns covered too.

  • @dendi1076
    @dendi1076 2 ปีที่แล้ว

    best explanation i could search about singleton after searching all over youtube/google. thank you!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      You're welcome, I'm so glad it was able to help you out! 😀

  • @matthewwheeler469
    @matthewwheeler469 ปีที่แล้ว +2

    Great video, man! Coming off Java, this topic was a little much to wrap my mind around. Also, probably the first thing that I've found that would be easier to do in Java than Python lol.
    Thanks for the help!

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      You're welcome Matthew, I'm glad you enjoyed the video! :-)

  • @jonathancarpenter6922
    @jonathancarpenter6922 2 ปีที่แล้ว

    Can't believe how clear you made this to understand!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      I'm really glad to hear it helped Jonathan! 😀

  • @ErikS-
    @ErikS- ปีที่แล้ว

    'simple' but controversial - and even despised by some - pattern.
    Excellent video and you gained a new subscriber.

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      Agreed 100% regarding the controversy… I fall in the pragmatic “it has its place” camp. And welcome aboard Erik! :-)

  • @polpriyanka
    @polpriyanka 5 วันที่ผ่านมา

    Very very helpful and clear and better to understand...thank you!

  • @vigneshr.3601
    @vigneshr.3601 2 ปีที่แล้ว

    Crystal clear explanation. I too like the second approach as it deals with general object class . Subscribed the channel 👍

  • @mohammadyahya78
    @mohammadyahya78 2 ปีที่แล้ว

    Thank you. At 13:00, why we need to call super class method to get back instance of Singleton class please? Can't we just do it without calling super(signleton, cls)?

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      Great question Mohammad! 🙂 I'll try my best to explain. We only call super(Singleton, cls).__new__(cls) the first time we need to make the Singleton instance. All subsequent times we use Singleton() the if-statement will detect that the instance is not None, i.e. that the instance exists, and we'll instead just return the instance. We do need to call super(Singleton, cls).__new__(cls) to actually make the object instance itself the first time though.

  • @Ragdoll333-q5l
    @Ragdoll333-q5l 2 ปีที่แล้ว +2

    I wish there are more design patterns in Python in this playlist!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      I’m planning to make more this spring and summer! :-D

  • @elias6406
    @elias6406 2 ปีที่แล้ว

    No words except THANK YOU! But disappointed you didn’t upload more design pattern videos 💔

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      You're welcome! :-) And I'll keep uploading more design pattern videos one day!

  • @Shashank_Shahi1989
    @Shashank_Shahi1989 3 ปีที่แล้ว +1

    Thank You for your videos.
    Please upload more videos on python design patterns if it's possible from your side.
    Thank You 👍

    • @PortfolioCourses
      @PortfolioCourses  3 ปีที่แล้ว +1

      Sounds good! I am hoping to do a lot more Python videos over the next year.

  • @aritzfloresmonje6183
    @aritzfloresmonje6183 6 หลายเดือนก่อน

    Great video! Very good example and explanation about singleton, although there is something I’m struggling to understand: what’s the difference between the __new__ and __init__ methods and when should we use each one of them?

    • @PortfolioCourses
      @PortfolioCourses  6 หลายเดือนก่อน

      Basically __new__ creates the object instance and __init__ initializes it (eg creates and initializes member variables), this article explains it in better detail: builtin.com/data-science/new-python. :-)

  • @daniellesprinzak7944
    @daniellesprinzak7944 ปีที่แล้ว

    thanks for the video! could you please explain super(Singleton,cls).__new__. what is happening here? is the new method accesed from object? what does super(Singleton, cls) do in this context?

  • @vaishnavi4354
    @vaishnavi4354 ปีที่แล้ว

    in the second way, if I write the __init__ method then it is instantiating the object 2 times . how to avoid this also? although the __new__ referances to the same address , still __init__ instantiates two times

  • @mallikarjunrterdal
    @mallikarjunrterdal ปีที่แล้ว

    What is there are two threads trying to create this object at the same time? Maybe both of them have checked __instance at the same time and found it to be None. Will it not create two different objects in this case?

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      We could use a lock if we need it to be thread safe. :-) medium.com/analytics-vidhya/how-to-create-a-thread-safe-singleton-class-in-python-822e1170a7f6

  • @lowgn9251
    @lowgn9251 หลายเดือนก่อน

    very clear, thank you very much !

  • @pavanjain2178
    @pavanjain2178 ปีที่แล้ว

    But it does not throw any exception if Singleton constructor is called for very first time instead of calling getInstance method, do we have any solution for this?

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      Well strictly speaking it's not a "problem" the way it is written now, so there isn't really a need for a "solution". If the constructor is called instead of calling getInstance, then the singleton is constructed, and that's fine, there is nothing wrong with that. The issue is if we try to use the constructor twice. If you want to design it differently and you just want to limit the client code (the code which uses the singleton pattern) to ONLY using getInstance then you could try something like this: stackoverflow.com/a/7346105. :-)

    • @pavanjain2178
      @pavanjain2178 ปีที่แล้ว

      @@PortfolioCourses yes the solution is fine and also thanks for letting me know the other solution on stack overflow. BTW your way of teaching is nice and lovely🤩

  • @a_72_saquibsheikh44
    @a_72_saquibsheikh44 3 ปีที่แล้ว

    Keep it up! Thank you very much.

  • @abdelmananabdelrahman4099
    @abdelmananabdelrahman4099 3 ปีที่แล้ว

    Great explanation

  • @davititchanturia
    @davititchanturia 2 ปีที่แล้ว

    Great, but in second approach __init__ method still get called and breaks current object.

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      I'm not experiencing this bug. The __init__ method should be called after the __new__ method, and it should be OK. I tried adding in an __init__ method to the 2nd approach to see if it would break anything, and I don't get any issue. Are you able to paste your code into a comment so I can check it out? I'm curious to understand what you mean.
      class Singleton2:
      __instance = None
      def __new__(cls):
      if (cls.__instance is None):
      cls.__instance = \
      super(Singleton2, cls).__new__(cls)
      return cls.__instance
      def __init__(self):
      print(self)
      s1 = Singleton2()
      print(s1)
      s2 = Singleton2()
      print(s2)
      s1.x = 5
      print(s2.x)

    • @davititchanturia
      @davititchanturia 2 ปีที่แล้ว

      @@PortfolioCourses class Singleton2:
      __instance = None
      def __new__(cls):
      if (cls.__instance is None):
      cls.__instance = \
      super(Singleton2, cls).__new__(cls)
      return cls.__instance
      def __init__(self):
      self.x=1
      def inc(self):
      self.x+=1
      s1 = Singleton2()
      s1.inc()
      s1.inc()
      s1.inc()
      print(s1.x) # 4
      s2 = Singleton2() ##
      s2.inc()
      print(s2.x) # 2 should be 6

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      @@davititchanturia OK I see what you mean. So strictly speaking the Singleton pattern is working fine, there is only ever one object instance of Singleton2. The problem is if you define __init__ then whenever you call Singleton2() to get the object instance, it will run. So any code in that __init__ function will essentially "re-initialize the object" in terms of setting attributes (i.e. member variables). It's the same object, but the x attribute is being set back to 1 when we have s2 = Singleton2(). To avoid this, we would want to do any initializing of object attributes in the __new__ function, like this code below. (And we will get 5, which is correct).
      We could then either use __init__ as a function to "re-initialize" the object, or just not define it at all. If I ever get to re-do this video, maybe I'll make a point to mention that to make it clearer how it needs to be used , but as it is now it will work OK in terms of only creating a single object instance.
      class Singleton2:
      __instance = None
      def __new__(cls):
      if (cls.__instance is None):
      cls.__instance = \
      super(Singleton2, cls).__new__(cls)
      cls.__instance.x=1
      return cls.__instance
      # def __init__(self):
      # self.x=1
      def inc(self):
      self.x+=1
      s1 = Singleton2()
      s1.inc()
      s1.inc()
      s1.inc()
      print(s1.x) # 4
      s2 = Singleton2() ##
      s2.inc()
      print(s2.x) # 2 should be 6

    • @davititchanturia
      @davititchanturia 2 ปีที่แล้ว

      @@PortfolioCourses thanks !!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      @@davititchanturia You're welcome Daviti! :-D

  • @nasriyosri5844
    @nasriyosri5844 2 หลายเดือนก่อน

    great vedio thnx

  • @surajbhattathiri
    @surajbhattathiri 3 ปีที่แล้ว

    Great content.
    Shouldnt we use not None instead of != None

    • @PortfolioCourses
      @PortfolioCourses  3 ปีที่แล้ว

      Thanks! Either will work. If we were working with a class where we had a custom comparison method for ==, it might matter, in this case with our Singleton we can be sure it will not matter as we do not define a custom comparison method. The answers here go into this a bit: stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none

  • @mlsanica7618
    @mlsanica7618 2 ปีที่แล้ว

    tf is this bro

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      What's the matter?

    • @mlsanica7618
      @mlsanica7618 2 ปีที่แล้ว

      @@PortfolioCourses In classical physics and general chemistry, matter is any substance that has mass and takes up space by having volume.