Python object-oriented nine custom class

Source: Internet
Author: User

First, custom class, the essence is we ourselves rewrite special functions

It __slots__ __xxx__ is important to note that these are similar to variables or function names, which have special uses in Python.

__slots__We already know how to use it, and __len__() we know it so that we can get class to len() function.

In addition, there are many special purpose functions in Python's class that can help us customize the class.

Second, __len__ () method

class mystr (str):    def __init__ (self, s):        = s    def __len__ (self):          return1
        >>> s = mystr ('abc')>>> Len (s) 2

Third, __str__ () method

class Student (object): ...     def __init__ (self         , name): ... = name     ... def __str__ (self         ): ... return ' Student Object (name:%s) ' % self.name ... >>> Print (Student ('Michael'object (Name:michael)

Iv. __repr__ () method

>>> s = Student ('Michael')>>> sobject  0x109afb310>

This is because the direct display of variable calls is not __str__() , but the __repr__() difference between the two is to return the string that the __str__() user sees, and the __repr__() string that the program developer sees, that __repr__() is, for debugging services.

The solution is to define one more __repr__() . But it's usually __str__() __repr__() the same as the code, so there's a lazy way to do it:

class Student (object):    def __init__ (self        , name): = name    def __str__ (self):         return ' Student Object (name=%s) ' % self.name    = __str__

V. __iter__ () method

If a class wants to be used for for ... in loops, like a list or a tuple, it must implement a __iter__() method that returns an iterative object, and the python for loop constantly calls the iteration object's method to get the __next__() next value of the loop until it encounters StopIterationexits the loop when the error occurs.

For the Fibonacci sequence, we write a fib class that can be used for a For loop:

 class  Fib (object   = 0 , 1   # Initialize two counters A, Def __iter__ (self):  return   Self # The instance itself is an iterative object, so return to its own def __next__: SELF.A, self.b 
     = self.b, SELF.A + self.b # calculates the next value  if  SELF.A > 100000  : # exit loop condition Raise Stopiterat Ion ()  return  SELF.A # Returns the next value 
 for inch Fib (): ...     Print (n) ... 1 1 2 3 5 ... 46368 75025

Vi. __getitem__ () method

classFib (Object): Def __getitem__ (self, n):ifIsinstance (N,int): # N is index A, b=1,1             forXinchrange (N): A, B= B, A +breturnaifisinstance (n, Slice): # N is the slice start=N.start Stop=N.stopifStart isNone:start=0A, B=1,1L= []             forXinchRange (stop):ifX >=Start:l.append (a) A, B= B, A +breturnL

But the step parameter is not processed,

There is no processing of negative numbers, so there __getitem__() is still a lot of work to be done to properly implement one.

In addition, if the object dict is considered, __getitem__() the argument may be an object that can be a key, for example str .

The corresponding method is to __setitem__() assign a value to the set as a list or a Dict object. Finally, there is a __delitem__() way to delete an element.

In short, by the above method, our own definition of the class and Python comes with the list, tuple, dict no difference, this is due to the dynamic language "duck type", do not need to force inheritance of an interface.

Python object-oriented nine custom class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.