Introduction to several common class methods in Python _python

Source: Internet
Author: User
Tags in python

Built-in method description

__init__ (self,...) Initializes an object that is called when a new object is created

__del__ (self) Frees the object and calls it before the object is deleted

Build actions for __new__ (CLS,*ARGS,**KWD) instances

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

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

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

__cmp__ (STC,DST) compares two objects src and DST

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

__SETATTR__ (S,name,value) Sets the value of the property

__delattr__ (s,name) Delete the Name property

The __getattribute__ () __getattribute__ () feature is similar to __getattr__ ()

__gt__ (Self,other) determines whether the self object is greater than the other object

__lt__ (Slef,other) determines whether 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 whether the self object is equal to other objects

__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 do some of the initialization you want for your object. Note that this name starts and ends with a double underline.

code example:

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

Output:

Hello, my name is Swaroop

Description: The __init__ method is defined to take a parameter name (and 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. Point numbers enable us to differentiate them. Most importantly, we do not call the __init__ method specifically, except that when creating a new instance of a class, the arguments are included in parentheses followed by the class name to pass to the __init__ method. This is an important part of this approach. Now we are able to use the Self.name domain in our approach. This has been validated in the Sayhi method.

__new__ ():

__new__ () is called before __init__ () to generate the instance object. This method and the properties of the class attribute can be used to implement the singleton pattern in the design pattern. A singleton pattern is the creation of a unique object, and a class designed by a singleton pattern can only instantiate an object.


#!/usr/bin/python
#-*-coding:utf-8-*-
class Singleton (object):
  __instance = None            # define instance
 
  def __ Init__ (self):
    pass
 
  def __new__ (CLS, *args, **KWD):     # Call the
    if __init__ is singleton.__instance before none:< c11/># generates a unique instance
      singleton.__instance = object.__new__ (CLS, *args, **KWD) return
    singleton.__instance

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

When you read a property of an object, Python automatically invokes the __getattr__ () method. For example, Fruit.color will be converted to fruit.__getattr__ (color). When you set a property by using an assignment statement, Python automatically invokes the _ The _setattr__ () method. __getattribute__ () is similar to __getattr__ () 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):        # Get Property method return
    Object . __getattribute__ (self, name)
 
  def __setattr__ (self, Name, value):
    self.__dict__[name] = value
 
if __name __ = = "__main__":
  fruit = fruit ("blue")
  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 of the sequence property. Suppose the fruit store sells more than one bell of fruit, and you can get no fruit from the fruit store by the __getitem__ () method.

code example:

#!/usr/bin/python
#-*-coding:utf-8-*-class fruitshop:
   def __getitem__ (self, I):   # Get fruit from the store
     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:

Banana

Apple 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__ () by the function str (). In this way, the object is associated with a string to facilitate the implementation of some programs that 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)      # calls the built-in function str () __str__ () method, the output result is: Fruit class
  Print fruit         #直接输出对象fruit, returns the value of the __str__ () method, and the output results are: Fruit class

__call__ ():

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

code example:

#!/usr/bin/python
#-*-Coding:utf-8-*-class
Fruit: Class
  growth:    # inner category
    def __call__ (self) :
      print "grow ..."
 
  grow = Growth ()   # calls Growth (), at which point the class growth is returned as a function, that is, the outer class fruit definition method Grow (), grow () will perform __ call__ () code
if __name__ = = ' __main__ ':
  fruit = fruit ()
  fruit.grow ()     # output Result: Grow ...
  Fruit.grow ()     # output Result: Grow ...

Related Article

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.