Usage instance of s and p in Python

  • 2020-04-02 14:03:17
  • OfStack

This article illustrates the use of s/p in Python with example s/p. Specific methods are as follows:

Let's take a look at the following sample code:


#call.py  a class It's loaded. 
class Next:
  List = []
  
  def __init__(self,low,high) :
    for Num in range(low,high) :
      self.List.append(Num ** 2)
  
  def __call__(self,Nu):
    return self.List[Nu]

If used like this:


b = Next(1,7)
print b.List
print b(2)

So feedback is normal:


[1, 4, 9, 16, 25, 36]
9

But if used like this:


b = Next
b(1,7)
print b.List
print b(2)
$python ./call.py
[1, 4, 9, 16, 25, 36]

Traceback (most recent call last):
 File "cal.py", line 17, in <module>
  print b(2) 
TypeError: __init__() takes exactly 3 arguments (2 given)

S/s is an initialization function that is executed while an instance of the class is being generated.

However, s/s is a simulated () call that needs to be applied on the instance, so this instance has already executed s/s of course.

The latter example you gave:


b = Next

Instead of creating an instance, you assign the class to a variable. Therefore, the following operations with b are all operations on the Next class, which is actually:


Next(1,7)
print Next.List
print Next(2)

I hope this article has helped you with your Python programming.


Related articles: