In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about the object-oriented use cases of python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
object-oriented
1. Create objects that support With statements
We all know how to use open or close statements, such as opening a file or acquiring a lock, but how do we implement our own methods?
You can use the _ _ enter__ and _ _ exit__ methods to achieve:
Class Connection: def _ init__ (self):... Def _ _ enter__ (self): # Initialize connection... Def _ _ exit__ (self, type, value, traceback): # Close connection... With Connection () as c: # _ _ enter__ () executes... # conn.__exit__ () executes
This is the most common way to implement context management in Python, but there is a simpler way:
From contextlib import contextmanager @ contextmanager def tag (name): print (f "") yield print (f "") with tag ("H2"): print ("This is Title.")
The above code snippet implements the content management protocol using the contextmanager manager decorator. When you enter the with block, execute the first part of the marking function (before yield), then execute the block, and finally execute the rest of the marking function.
two。 The skill of overloading operational symbols
Considering that there are many comparison operators: _ _ lt__, _ _ le__, _ _ gt__, it can be annoying for a class to implement all comparison operators. You can use functools.total_ordering at this time:
From functools import total_ordering @ total_ordering class Number: def _ _ init__ (self, value): self.value = value def _ lt__ (self, other): return self.value
< other.value def __eq__(self, other): return self.value == other.value print(Number(20) >Number (3)) print (Number (1)
< Number(5)) print(Number(15) >= Number (15) print (Number (10) > > type (None) > type (abs)
The corresponding class type is returned for the class object type (). The following is to determine whether the type types of the two variables are the same:
> type (11) = = type (22) True > type ('abc') = = str True > type (' abc') = = type (33) False
Isinstance (): can show whether an object is of a certain type
Class Husty (Dog):... Pass. > > a = Animal () > > b = Dog () > > c = Husty () > isinstance (cMagneHusty) True > isinstance (cmaideDog) True > isinstance (cMagine Animal) True > isinstance (bMagazine) False
Husty is an object of type Husty, Dog, Animal, but Dog cannot be said to be an object of Husty.
Dir (): used to get all the methods and properties of an object. The return value is a list that contains a string:
> dir ('abc') [' _ _ add__','_ _ class__',. '_ _ hash__',' _ _ init__','_ _ I. Isalnum 'isidentifier',' islower',. 'translate',' upper', 'zfill']
Among them, properties and methods like _ _ xx__ have a special purpose. If you call the len () function view to get the length of an object, the _ _ len__ () method of the object is called automatically inside the len () function.
5. Iterator and slice
If you slice the Iterator directly, you will get TypeError, indicating that the generator object cannot be asked with a subscript, but there is a trick:
Import itertools s = itertools.islice (range (50), 10,20) for val in s:.
Using itertools.islice, you can create an islice object that is an iterator that generates the desired project. However, this consumes all generator items until slicing begins, and it also consumes all items in the islice object.
6. Skip some lines
Sometimes, you must use a known variable number of unwanted lines (such as comments). You can also use itertools:
String_from_file = "" / / Author:. / / License:. / Date:. Actual content... "" Import itertools for line in itertools.dropwhile (lambda line: line.startswith ("/ /"), string_from_file.split ("\ n"): print (line)
This code snippet generates lines only after the initial comment section. This method is useful if you only want to discard it at the beginning of the iterator and you don't know how many items are in it.
7. Named slicing
Using a large number of hard-coded index values can easily lead to tedious code and damage code readability. A common technique is to use constants for index values, but we can also use named slices:
In the example, you can see that you can index them by first naming them using the slice function, and then using them when cutting out a portion of the string. You can also use the properties of the slice object .start, .stop, and .step for more information.
Thank you for reading! This is the end of this article on "python object-oriented use cases". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.