Singleton Design Pattern - Advanced Python Tutorial #9

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 ต.ค. 2024

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

  • @xzex2609
    @xzex2609 ปีที่แล้ว +8

    A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are: To limit concurrent access to a shared resource.

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

      I wanted to ask for more elaboration on the benefit you provided and perhaps other benefits this pattern brings?

  • @DominatorIII
    @DominatorIII 3 ปีที่แล้ว +37

    I was missing the explanation, on why you would do this? What are the applications? And why always use person as an example, which doesn't say anything. Couldn't you have used a more applied example? Other than that, I love your videos! Please keep up the good work!

    • @darsh_shukla
      @darsh_shukla 3 ปีที่แล้ว +16

      Consider a large code base, in which there are multiple modules that share config files. Instead of reading the files multiple times (too many I/O) across these modules we read it only once.
      Singleton is abstraction or illusion to share objects and states globally.

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

      Think about designing a game of chess where you would wan't to save the state of the game in a class.. now you would want only one instance of the class in the whole software....
      That's where we can use singleton

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

      same here, he never explains why???

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

      It’s like taking a unique snapshot of the state?

  • @HerptieDerper
    @HerptieDerper 3 ปีที่แล้ว +9

    I swear I learn more from you than from college

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

      fu** college ,
      i got nothing from that hell hole.

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

    Why do you need to create an interface for this singleton example??🤔🤔

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

    Python programmers almost never implement the Singleton Pattern as described in the Gang of Four book, whose Singleton class forbids normal instantiation and instead offers a class method that returns the singleton instance. Python is more elegant, and lets a class continue to support the normal syntax for instantiation while defining a custom __new__() method that returns the singleton instance. But an even more Pythonic approach, if your design forces you to offer global access to a singleton object, is to use The Global Object Pattern instead.

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

    Can we make this pattern look more "pythonic" by overriding the __new__ static method instead of introducing get_instance?

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

      more like the metaclass would override the __call__ function instead

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

    great video, i'm actually learning a from the *design pattern* videos

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

    thank you floren. need more video on the rest of the common design pattern.

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

    These series is excellent, thanks!

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

    And what would be the point of this?

  • @АлександрНикитин-э5ы8э
    @АлександрНикитин-э5ы8э 2 ปีที่แล้ว +2

    implementation using decorator
    def singleton(cls):
    instances = {}
    def getinstance():
    if cls not in instances:
    instances[cls] = cls()
    return instances[cls]
    return getinstance
    @singleton
    class MyClass:
    ...

    • @АлександрНикитин-э5ы8э
      @АлександрНикитин-э5ы8э 2 ปีที่แล้ว +1

      implementation using meta-class
      class MetaSingleton(type):
      _instances = {}
      def __call__(cls, *args, **kwargs):
      if cls not in cls._instances:
      cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
      return cls._instances[cls]
      class MyClass(metaclass=MetaSingleton):
      ...

  • @AhmadAlfan-d2h
    @AhmadAlfan-d2h 8 หลายเดือนก่อน

    Just what I needed, thank you so much!

  • @MrWadood007
    @MrWadood007 3 ปีที่แล้ว +4

    Hey! A very clear explanation as usual. A suggestion, you could display your video on the bottom left , that way it won't block any text.

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

    3:09 Never use sth == None. pep8 does not recommend that. Instead, use sth is None.

  • @SparePlayss
    @SparePlayss 3 ปีที่แล้ว +14

    imagine being a complete python noob and watching this..

    • @NeuralNine
      @NeuralNine  3 ปีที่แล้ว +7

      Hahahaha I hope they would read "Advanced" before watching ^^

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

      @@NeuralNine they should..

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

      @@NeuralNine 🤣🤣🤣

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

    Great explanation! I'm still trying to figure out where this pattern can be used. Anyway. Thanks!

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

      A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are: To limit concurrent access to a shared resource.

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

      Imagine a game with a player class. There should only ever be one instance of player, and it needs to be accessed from many other classes. Using a singleton for player makes it easy to get a reference to this player instance from any class which needs to.

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

    Why do we need, or do we need the IPerson class at all?

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

    Why creating get_instance method if you don't use it ?

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

    Really you are the best bro!!!!!!!!!!👍👍👍

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

    I think you should add thread lock. So it will make it thread safe

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

    Can we inherit from this singleton class?

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

    Shouldnt this work without using Metaclass?

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

      yes it should, I think he implemented it the way he did so that'd it'd be similar to a Java singleton

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

    Nicely explained. But if you call get_instance() before PersonSingleton(), then it will return None, you forgot to do cls.__instance == PersonSingleton(*args)

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

    Great video but you should be using 'is' and 'is not' for comparison against None.

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

    Hi bro . Help me I can't understand about this pattern topic can you explain pls? And how many types are there?

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

    This solution, to some extent confuses singleton with static, unfortunately. A singleton object does not use static data and uses a factory for creation.

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

    This guy looks like Henry Cavill! Keep up the good work.

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

    Great explanation. Thanks

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

    Thanks for sharing!

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

    nice one

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

    Great tutorial

  • @darsh_shukla
    @darsh_shukla 3 ปีที่แล้ว +13

    Don't treat Python as Java. There are better ways to deal with the Singleton functionality.

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

      Like as ??😊

  • @s.aravindh6227
    @s.aravindh6227 3 ปีที่แล้ว +1

    Nice bro 👍👍

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

    Can you do a video course to make a discord bot?

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

      I also said him in the last vid for discord.py

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

      Yea!!

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

    why does he look like a 3d rendered model?

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

    awesome !!!

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

    It’s great

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

    This is an overly-complex solution. Don't need any abstractions or classes. All you need is a global variable + 1 function.
    Feels like you're writing Java in Python my dude.

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

      This is actually the correct way and how you should do it in production.

  • @anasbadr9372
    @anasbadr9372 3 ปีที่แล้ว +7

    Fun fact: fun fact is fun

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

    please, continue)

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

    there is a pythonic way for singleton

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

    I Want BETTER GUI CHAT :):):)

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

    Cool tutorial! However, the get_instance and print_data should be class methods!

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

      For the pattern, you actually only need the class member __instance and the logic in the __init__ function with the get_instance function.

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

      print_data kind of exists as the __str__
      method

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

    make metaclass tutorial please

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

    u look like gta charector

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

    If you are noob in python ! Don't watch this

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

    Nice video! What about RJVX12 algorithm review?

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

    from abc import ABCMeta, abstractstaticmethod
    class IPerson(metaclass=ABCMeta):
    @abstractstaticmethod
    def get_data():
    """Implement in child class"""
    class SingletonPattern(IPerson):
    __instance = None
    def __new__(cls, *args, **kwargs) -> None: # new is already a static dunder method.
    if not cls.__instance:
    cls.__instance = super().__new__(cls)
    return cls.__instance

    def __init__(self, username):
    # if not hasattr(self, "username"): prevents many instances
    self.username = username
    # else:
    # raise Exception("This class is a singleton") notifies error
    @staticmethod
    def get_data():
    print(f"Username: {SingletonPattern.__instance.username}")
    if __name__ == "__main__":
    person = SingletonPattern("Kevin").get_data()
    person = SingletonPattern("John").get_data()