Describes several commonly used class methods in Python
- 2020-05-07 19:55:52
- OfStack
Built-in method description
__init__ (self,...). Initializes an object, called when a new object is created
s 9en__ (self) releases the object and is invoked before the object is deleted
S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S
s 21en__ (self) is called with the print statement
S 26en s 27en__ (self,key) gets the corresponding value of the index key of the sequence, which is equivalent to seq[key]
s 36en__ (self) is called when the inline function len() is called
s 42en__ (stc,dst) compare two objects src and dst
s 50en__ (s,name) gets the value of the property
S 55en s 56en__ (s,name,value) sets the value of the property
S 62en s 63en__ (s,name) delete the name property
S 69en s s 70en__ () s 71en__ () s function is similar to that of s 72en__ () s
S 75en s 76en__ (self,other) determines whether the self object is larger than the other object
S 83en s 84en__ (slef,other) determines whether the self object is less than the other object
S 91en s 92en__ (slef,other) to determine whether the self object is greater than or equal to the other object
S 99en s s 100en__ (slef,other) determine whether the self object is less than or equal to the other object
S 107en s 108en__ (slef,other) to determine whether the self object is equal to the other object
s 116en__ (self,*args) calls the instance object as a function
__init__():
The method runs immediately after 1 object of the class is established. This method can be used to initialize your object as much as you want. Notice that the name begins and ends with a double underscore.
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: s 142en method is defined to take 1 parameter name (and the normal parameter self). In this __init__, we simply create a new domain, also known as name. Notice that they are two different variables, even though they have the same name. The dots allow us to distinguish them. Most importantly, we do not call the method with a special function called s 149en__, but simply pass the arguments to s 150en__ method with the parenthesis following the class name when creating a new instance of the class. That's the important thing about this approach. Now we can use the self.name field in our method. This is verified in the sayHi method.
__new__():
The singleton pattern in the design pattern can be implemented by taking advantage of the properties of this method and the class properties.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Singleton(object):
__instance = None # Define the instance
def __init__(self):
pass
def __new__(cls, *args, **kwd): # in __init__ Before the call
if Singleton.__instance is None: # Generated only 1 The instance
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance
S. 173en s. 175en__ (), s. 176en__ () and s
For example, fruit.color will be converted to fruit.s. Use to get the value of the property. But with s 192en__ () you can provide better control and the code is more robust. Note that s 194en__ () 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 a property
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") # To obtain color attribute
fruit.__dict__["_Fruit__price"] = 5
print fruit.__dict__.get("_Fruit__price") # To obtain price attribute
__getitem__():
If the class defines an attribute as a sequence, you can output an element of the sequence attribute using successive s 209en__ (). Assuming that more than one serving of fruit is available in the fruit store, you can use successive s 210en__ () to get all the fruit in the fruit store
Code example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-class FruitShop:
def __getitem__(self, i): # Get the fruit from the fruit store
return self.fruits[i]
if __name__ == "__main__":
shop = FruitShop()
shop.fruits = ["apple", "banana"]
print shop[1]
for item in shop: # Export fruit from the fruit store
print item,
The output is:
banana
apple banana
__str__():
S 231en__ () is used to represent the meaning of the object and return 1 string. With the implementation of the method of s 232en__ (), you can either output the object directly using the s 233en statement or trigger the execution of s 235en__ () by using the function s 234en ()
Code example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit:
'''Fruit class ''' # for Fruit Class defines a docstring
def __str__(self): # Defines a string representation of an object
return self.__doc__
if __name__ == "__main__":
fruit = Fruit()
print str(fruit) # Calling the built-in function str() Set out __str__() Method, the output result is :Fruit class
print fruit # Direct output object fruit, return __str__() Method, the output is :Fruit class
__call__():
Implement the s 250en__ () method in the class to return the contents of s 251en__ () directly on object creation. Use this method to simulate the static method
Code example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit:
class Growth: # The inner class
def __call__(self):
print "grow ..."
grow = Growth() # call Growth() , at this point will class Growth Return as a function , Is an external class Fruit Define methods grow(),grow() Will perform __call__() The code in
if __name__ == '__main__':
fruit = Fruit()
fruit.grow() # Output results: grow ...
Fruit.grow() # Output results: grow ...