Python Object-oriented (ii) built-in class method __python

Source: Internet
Author: User
Built-in methods Description
__init__ (self,...) Initializes an object that is called when a new object is created
__del__ (self) Frees the object to be invoked before the object is deleted
__new__ (CLS,*ARGS,**KWD) Build actions for instances
__str__ (self) Called when the print statement is used
__getitem__ (Self,key) Gets the value of the index key for the sequence, equivalent to Seq[key]
__len__ (self) Called when the inline function len () is called
__cmp__ (STC,DST) Compare two objects src and DST
__getattr__ (s,name) Get the value of a property
__setattr__ (S,name,value) Set the value of a property
__delattr__ (s,name) Remove the Name property
__getattribute__ () The __getattribute__ () feature is 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) To determine if the self object is greater than or equal to the other object
__le__ (Slef,other) To determine if the self object is less than or equal to the other object
__eq__ (Slef,other) To determine whether the Self object equals other objects
__call__ (Self,*args) Call 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 invoked before __init__ (). Used to generate an instance object. The use of this method and the attributes of the class 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 that is designed by a singleton pattern 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): # called before __init__
If Singleton.__instance is None: # 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): # Methods to get Properties
Return object.__getattribute__ (self, name)

def __setattr__ (self, Name, value):
Self.__dict__[name] = value

if __name__ = = "__main__":
Fruit = fruit ("Blue", 10)
Print Fruit.__dict__.get ("_fruit__color") # Get 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 a fruit store
return Self.fruits[i]

if __name__ = = "__main__":
Shop = Fruitshop ()
Shop.fruits = ["Apple", "banana"]
Print Shop[1]
For item in shop: # Output Fruit Store
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:
"' The Fruit class ' #为Fruit类定义了文档字符串
def __str__ (self): # defines a string representation of an object
Return self.__doc__

if __name__ = = "__main__":
Fruit = fruit ()
Print str (fruit) # calls the built-in function str () departure __str__ () method, the output is: Fruit class
Print Fruit #直接输出对象fruit, returns the value of the __str__ () method, the output is: 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 classes
def __call__ (self):
Print "Grow ..."

Grow = Growth () # calls growth (), at which time the class growth is returned as a function, that is, the outer class fruit definition method Grow (), grow () executes the code within __CALL__ ()
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.