I'm recently working on design patterns in python and I saw this in the singleton design pattern:
# THIS WILL BE USED AS METACLASS FOR OTHER CLASSES
class MetaSingleton(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super().__call__(*args, **kwargs)
return cls._instance[cls]
And also I understood that __call__
is class method. But I remembered that I use __call__
with self
like this:
class myclass:
def __call__(self):
print('__call__ is called.')
x = myclass()
x()
# __call__ is called.
(These two codes are not related to each other, they are just examples.)
So __call__
method is class method or object method?
And also another question: If it's class method, In which situations I can use it as a classmethod?
It's an instance method. If it were a class method, it would be decorated with classmethod
. The name of the first argument is irrelevant. It can be banana
if you want
— from juanpa.arrivillaga 's comment
it's an instance method, but instances of metaclasses are classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.