In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use HTML5__init__,__new__,__call__methods". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "how to use HTML5_init__,__new__,__call__methods" together!
Everything has a process from creation to use to death, and objects have a similar fate in the object-oriented programming model of programming languages: creation, initialization, use, garbage collection, and different methods (roles) are responsible for different stages.
When asked about object-oriented methods in an interview, it is inevitable to ask__init__,__new__,__call__methods, which are the most commonly used magic methods. Here are a few ways to clarify the use of these methods:
1. __init__method
The__init__method is responsible for initializing the object. Before the system executes the method, the object already exists. Otherwise, what is initialized? Let's start with an example:
class Dog:
def __init__(self):
print("__init__ ")
super(A, self).__ init__()
def __new__(cls):
print("__new__ ")
return super(A, cls).__ new__(cls)
def __call__(self): #You can define arbitrary parameters
print('__call__ ')
Dog()
The output is:
__new__
__init__
From the output, the__new__method is called first, returning an instance object, and then__init__is called.__ The call__method is not called, so let's leave that to the end. Let's talk about the first two methods first, and rewrite them slightly:
def __init__(self):
print("__init__ ")
print(self)
super(A, self).__ init__()
def __new__(cls):
print("__new__ ")
self = super(A, cls).__ new__(cls)
print(self)
return self
The output is:
__init__
From the output, the return value of the__new__method is the instance object of the class, which is passed to the self parameter defined in the__init__method so that the instance object can be initialized correctly.
If the__new__method does not return a value (or returns None) then__init__will not be called, which makes sense because the instance object has not been created, and there is no point in calling init. Python also stipulates that__init__can only return None, otherwise it will report an error.
The__init__method can be used to do some initialization work, such as initializing the state of the instance object:
def __init__(self, a, b):
self.a = a
self.b = b
super(A, self).__ init__()
In addition, all parameters defined in the__init__method except self must be identical or equivalent to the parameters defined in the__new__method except cls.
class B:
def __init__(self, *args, **kwargs):
print("init", args, kwargs)
def __new__(cls, *args, **kwargs):
print("new", args, kwargs)
return super().__ new__(cls)
B(1, 2, 3)
#Output
new (1, 2, 3) {}
init (1, 2, 3) {}
2. __new__method
Normally we don't rewrite this method unless you know exactly how to do it, when do you care about it, it's used as a constructor to create objects, it's a factory function dedicated to producing instance objects. One of the famous design patterns, the singleton pattern, can be implemented in this way.
class DatabasePools:
_singleton = None
def __new__(cls, *a, **k):
if not cls._ singleton:
cls._ singleton = object.__ new__(cls, *a, **k)
return cls._ singleton
This is one way to implement the singleton pattern through the__new__method, which returns the instance directly if it exists, and creates an instance first if it doesn't.
Summary:
__ new__is used to create an object with a return value;__new__is a class method;__ init__is used to initialize an object with no return value
__new__default parameter is cls, the system passes the class name,__init__default parameter is self, the system passes the current object
__ new__executes before__ init__
3. __call__method
About__call__method, we have to mention a concept first, that is, callable object (callable), we usually custom functions, built-in functions and classes are callable objects, but can put a pair of brackets () applied to an object can be called callable object, to determine whether the object is callable object can be used function callable
If the__call__method is implemented in the class, then the instance object will also become a callable object, so let's go back to the first example:
a = Dog()
print(callable(a)) # True
A is an instance object and also callable, so I can call it like a function. Try:
a() # __call__
It's amazing that instance objects can also be used as callable objects like functions. So, what kind of scenarios can this feature be used in? This should be combined with the characteristics of the class, the class can record data (attributes), but the function does not (closure is also feasible in a sense), using this feature can be implemented based on the class decorator, in the class inside the record state, for example, the following example is used to record the number of times the function is called:
class Counter:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@Counter
def foo():
pass
for i in range(10):
foo()
print(foo.count) # 10 Thank you for reading, the above is "how to use HTML5__init__,__new__,__call__method" content, after the study of this article, I believe that everyone on how to use HTML5__init__,__new__,__call__method This problem has a deeper understanding, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.