Объекты a и b указывают на один и тот же экземпляр класса Singleton, поэтому a is b возвращает True. Это стало возможным благодаря специальной логике в методе __new__, который отвечает за создание объекта. В классе Singleton есть класс-переменная _instance, где хранится единственный созданный объект.
При первом вызове конструктора Singleton(10) переменная _instance пуста, и __new__ создает новый объект. Этот объект сохраняется в _instance, и далее возвращается. При втором вызове Singleton(20) метод new видит, что _instance уже существует, и возвращает его же, не создавая новый. Таким образом, a и b — это ссылки на один и тот же объект. Метод __init__ при этом всё равно вызывается повторно, и устанавливает self.value = 20, затирая предыдущее значение. Это тонкость: __new__ управляет созданием, а __init__ вызывается каждый раз, даже если объект не создавался заново. Такой шаблон называется синглтон — он гарантирует, что у класса будет только один экземпляр.
class Singleton: _instance = None # Класс-переменная, где будет храниться единственный экземпляр
def __new__(cls, *args, **kwargs): # Этот метод вызывается ПЕРЕД __init__, чтобы создать объект if cls._instance is None: # Если объект еще не создан — создаем его через стандартный способ cls._instance = super().__new__(cls) # Если уже создан — просто возвращаем его return cls._instance
def __init__(self, value): # Этот метод вызывается КАЖДЫЙ РАЗ, даже если объект уже существует self.value = value # Значение перезаписывается при каждом вызове
# Создаем первый экземпляр a = Singleton(10)
# Пытаемся создать второй экземпляр с другим значением b = Singleton(20)
print(a.value) # 20 — потому что __init__ второй раз перезаписал значение print(b.value) # 20 — это тот же объект, что и a, с тем же атрибутом print(a is b) # True — это один и тот же объект в памяти
Объекты a и b указывают на один и тот же экземпляр класса Singleton, поэтому a is b возвращает True. Это стало возможным благодаря специальной логике в методе __new__, который отвечает за создание объекта. В классе Singleton есть класс-переменная _instance, где хранится единственный созданный объект.
При первом вызове конструктора Singleton(10) переменная _instance пуста, и __new__ создает новый объект. Этот объект сохраняется в _instance, и далее возвращается. При втором вызове Singleton(20) метод new видит, что _instance уже существует, и возвращает его же, не создавая новый. Таким образом, a и b — это ссылки на один и тот же объект. Метод __init__ при этом всё равно вызывается повторно, и устанавливает self.value = 20, затирая предыдущее значение. Это тонкость: __new__ управляет созданием, а __init__ вызывается каждый раз, даже если объект не создавался заново. Такой шаблон называется синглтон — он гарантирует, что у класса будет только один экземпляр.
class Singleton: _instance = None # Класс-переменная, где будет храниться единственный экземпляр
def __new__(cls, *args, **kwargs): # Этот метод вызывается ПЕРЕД __init__, чтобы создать объект if cls._instance is None: # Если объект еще не создан — создаем его через стандартный способ cls._instance = super().__new__(cls) # Если уже создан — просто возвращаем его return cls._instance
def __init__(self, value): # Этот метод вызывается КАЖДЫЙ РАЗ, даже если объект уже существует self.value = value # Значение перезаписывается при каждом вызове
# Создаем первый экземпляр a = Singleton(10)
# Пытаемся создать второй экземпляр с другим значением b = Singleton(20)
print(a.value) # 20 — потому что __init__ второй раз перезаписал значение print(b.value) # 20 — это тот же объект, что и a, с тем же атрибутом print(a is b) # True — это один и тот же объект в памяти
BY Python: задачки и вопросы
Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283
From the Files app, scroll down to Internal storage, and tap on WhatsApp. Once you’re there, go to Media and then WhatsApp Stickers. Don’t be surprised if you find a large number of files in that folder—it holds your personal collection of stickers and every one you’ve ever received. Even the bad ones.Tap the three dots in the top right corner of your screen to Select all. If you want to trim the fat and grab only the best of the best, this is the perfect time to do so: choose the ones you want to export by long-pressing one file to activate selection mode, and then tapping on the rest. Once you’re done, hit the Share button (that “less than”-like symbol at the top of your screen). If you have a big collection—more than 500 stickers, for example—it’s possible that nothing will happen when you tap the Share button. Be patient—your phone’s just struggling with a heavy load.On the menu that pops from the bottom of the screen, choose Telegram, and then select the chat named Saved messages. This is a chat only you can see, and it will serve as your sticker bank. Unlike WhatsApp, Telegram doesn’t store your favorite stickers in a quick-access reservoir right beside the typing field, but you’ll be able to snatch them out of your Saved messages chat and forward them to any of your Telegram contacts. This also means you won’t have a quick way to save incoming stickers like you did on WhatsApp, so you’ll have to forward them from one chat to the other.
Should I buy bitcoin?
“To the extent it is used I fear it’s often for illicit finance. It’s an extremely inefficient way of conducting transactions, and the amount of energy that’s consumed in processing those transactions is staggering,” the former Fed chairwoman said. Yellen’s comments have been cited as a reason for bitcoin’s recent losses. However, Yellen’s assessment of bitcoin as a inefficient medium of exchange is an important point and one that has already been raised in the past by bitcoin bulls. Using a volatile asset in exchange for goods and services makes little sense if the asset can tumble 10% in a day, or surge 80% over the course of a two months as bitcoin has done in 2021, critics argue. To put a finer point on it, over the past 12 months bitcoin has registered 8 corrections, defined as a decline from a recent peak of at least 10% but not more than 20%, and two bear markets, which are defined as falls of 20% or more, according to Dow Jones Market Data.