Introduction to several common class methods in Python

Source: Internet
Author: User
Built-in method description

__init__ (self,...) initializes the object, which is called when a new object is created

__del__ (self) Releases the object, which is called before the object is deleted

__new__ (CLS,*ARGS,**KWD) Instance generation action

__str__ (self) is called when the print statement is used

__getitem__ (Self,key) Gets the value corresponding to the index key of the sequence, equivalent to Seq[key]

__len__ (self) is called when the inline function len () is called

__cmp__ (STC,DST) Comparison of two objects Src and DST

__GETATTR__ (s,name) Gets the value of the property

__setattr__ (s,name,value) Setting the value of a property

__DELATTR__ (s,name) Remove the Name property

__GETATTRIBUTE__ () __getattribute__ () function similar to __getattr__ ()

__gt__ (Self,other) to determine if the self object is greater than the other object

__lt__ (Slef,other) to determine if the self object is less than the other object

__GE__ (Slef,other) determines whether the self object is greater than or equal to the other object

__LE__ (Slef,other) determines whether the self object is less than or equal to the other object

__EQ__ (Slef,other) determines if the self object is equal to the other object

__CALL__ (Self,*args) calls the instance object as a function

__init__ ():

The __init__ method runs immediately when an object of the class is established. This method can be used to initialize your object with some of the things you want. Note that the start and end of this name are double underlines.

code example:

#!/usr/bin/python# Filename:class_init.pyclass Person:  def __init__ (self, name):    self.name = name  def Sayhi (self):    print ' Hello, my name is ', SELF.NAMEP = person (' Swaroop ') P.sayhi ()

Output:

Hello, my name is Swaroop

Description: The __init__ method is defined as taking a parameter name (as well as the normal argument self). In this __init__, we just create a new domain, also known as name. Note that they are two different variables, although they have the same name. The dot number allows us to differentiate between them. Most importantly, we do not specifically call the __init__ method, but when creating a new instance of a class, include the parameters in parentheses followed by the class name, which is passed to the __init__ method. This is the important point of this method. Now, we are able to use the Self.name domain in our methods. This has been verified in the Sayhi method.

__new__ ():

__new__ () is called before __init__ () to generate an instance object. The singleton pattern in the design pattern can be realized by using this method and the properties of the class. Singleton mode refers to the creation of unique objects, and the singleton pattern-designed class can only instantiate an object.


#!/usr/bin/python#-*-coding:utf-8-*-class Singleton (object):  __instance = None            # definition Instance   def __init__ (self ):    pass   def __new__ (CLS, *args, **KWD):     # calls before __init__    if Singleton.__instance is None:  # generates a unique instance C8/>singleton.__instance = object.__new__ (CLS, *args, **KWD)    return singleton.__instance

__getattr__ (), __setattr__ () and __getattribute__ ():

When you read a property of an object, Python automatically calls the __getattr__ () method. For example, Fruit.color is converted to fruit.__getattr__ (color). When you set a property using an assignment statement, Python automatically calls the _ _setattr__ () method. The function of __getattribute__ () is similar to __getattr__ (), which is used to get the value of the property. But __getattribute__ () can provide better control, The code is more robust. Note that the __setattribute__ () method does not exist in Python.

code example:

#!/usr/bin/python#-*-coding:utf-8-*-class Fruit (object):  def __init__ (self, color = "red", Price = 0):    self.__ color = Color    Self.__price = Price       def __getattribute__ (self, name):        # method to get Properties    return object.__ getattribute__ (self, name)   def __setattr__ (self, Name, value):    Self.__dict__[name] = value if __name__ = = "__ main__ ":  fruit = fruit (" Blue "," ten ")  print Fruit.__dict__.get (" _fruit__color ")    # Get the Color property  fruit.__ dict__["_fruit__price"] = 5  print fruit.__dict__.get ("_fruit__price")    # Get the Price property

__GETITEM__ ():

If a class defines a property as a sequence, you can use __getitem__ () to output an element in a sequence property. Suppose that fruit stores sell more than a few minutes of fruit, you can get the fruit shop by __getitem__ () method of fruit

code example:

#!/usr/bin/python#-*-coding:utf-8-*-class fruitshop:   def __getitem__ (self, I):   # gets fruit store Fruit     return Self.fruits[i]   if __name__ = = "__main__": Shop  = Fruitshop ()  shop.fruits = ["Apple", "banana"]  print SHOP[1]  for item in shop:        # output Fruit Store fruit    Print Item,

The output is:

Bananaapple Banana

__STR__ ():

__STR__ () is used to represent what the object represents and returns a string. After implementing the __str__ () method, you can output the object directly using the print statement, or you can trigger the __str__ () from the function str () The execution of the. This associates the object with a string to facilitate implementation of certain programs, which can be used to represent a class

code example:

#!/usr/bin/python#-*-coding:utf-8-*-class Fruit:     ' Fruit class '        #为Fruit类定义了文档字符串  def __str__ (self):     # Defines the string representation of the object    return self.__doc__ if __name__ = = "__main__":  fruit = fruit ()  print str (fruit)      # Call the built-in function str () departure __str__ () method, the output is: Fruit class  Print fruit         #直接输出对象fruit, return the value of the __str__ () method, the output is: Fruit class

__call__ ():

Implement the __call__ () method in a class to return the contents of __call__ () directly when the object is created. Use this method to simulate a static method

code example:

#!/usr/bin/python#-*-coding:utf-8-*-class Fruit:  class Growth:    # inner    def __call__ (self):      print "Grow ..."   grow = Growth ()   # calls Growth (), at which time class growth is returned as a function, that is, the method fruit () is defined for the outer class grow (), and grow () will execute the code within __CALL__ () if _ _name__ = = ' __main__ ':  fruit = fruit ()  fruit.grow ()     # output: Grow ...  Fruit.grow ()     # output: Grow ...
  • 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.