Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python generators and classes

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "Python generator and class how to use", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "Python generator and class how to use" it!

Generator

One way to create your own iterator is to use generator functions. The generator function uses the yield keyword to pass the next iterator value to the caller. This is similar to keywords in yield returnC#. Once the function returns, there is nothing to iterate over.

Let's yield use the generator function to demonstrate the keyword, which generates the first n digits of the Fibonacci sequence:

Def fibonacci (n): a = 1b = 1 for i in range (n): if I < 2: yield 1 else: C = a + b a = b b = c yield c

You can now use this function range as you would with a function such as, for example, in a loop:

For f in fibonacci (10): print (f)

This will print the first ten Fibonacci numbers.

You can also use the generator function to generate an infinite number of elements.

Class

Like C # or Java, Python has classes. Python provides all the standard features of object-oriented programming.

Let's look at an example of a simple class in Python:

From math import sqrtclass Vector: def _ init__ (self, x, y): self.x = x self.y = y def length (self): return sqrt (self.x * * 2 + self.y * * 2)

The _ _ init__ method is a constructor.

Length is a class method

The first parameter of a class method refers to the instance of the class being processed. By convention, this is called self. You can name it another name, but no one has ever done so. The role of self is much like that in thisC# and Java, that is, a reference to the current object. The difference in Python is that you can't just use x instead of self.x, and Python requires you to explicitly include it as the first method parameter.

You can now use the class like this:

V = Vector (1,1) print (v.length ()) print (v.x) print (v.y)

The x and y properties are available when you see the access above, but they can be modified, as well:

V.x = 2print (v.length ())

Private does not have access modifiers such as publicand for Python. All variables are publicly accessible. The property name at the beginning of the underscore is a way to tell users of your class that they should not use the property, but this is not enforced by the language.

Inherit

Let's demonstrate how to derive from a class in Python. We will create a base class Document and a derived class Book:

Class Document: def _ init__ (self, author, content): self.author = author self.content = content def length (self): return len (self.content) def info_summary (self): return "Document written by" + self.authorclass Book (Document): def _ init__ (self, author, content, pages): super (). _ init__ (author Content) self.pages = pages def info_summary (self): return "Book written by {} of {} pages" .format (self.author, self.pages)

The Book class is derived from Document. In the _ _ init__ method of the Book class, this line calls the constructor of the superclass.

Super (). _ init__ (author, content)

The info_summary function is overridden by in Book (override doesn't need keywords or anything like that), and there's no mention of lengthinBook, so it's just from Document.

Book = Book ("me", "... content...", 50) print (book.length ()) print (book.info_summary ())

If you want to check whether an object belongs to a class, use the following isinstance function:

Print (isinstance (book, Book)) # Trueprint (isinstance (book, Document)) # Trueprint (isinstance (book, object)) # Truedoc = Document ("someone else", "...") print (isinstance (doc, Book)) # Falseprint (isinstance (doc, Document) # True

Unlike C # and Java, Python supports multiple inheritance: Book (Document) you can write class instead of class Book (Document, AnotherClass, PerhapsEvenMore).

If the superclass has a method with the same name, only one of them can be derived in the subclass. When a method is called (not explicitly overridden), Python uses an algorithm called C3 linearization to determine the order of lookups in the superclass. If you want to see the so-called method parsing order, you can look at the YourClassName.__mro__ property. This is a man-made example to prove

Class A: passclass B: passclass C: passclass D (A, C): passclass F (B, C): passclass G (A): passclass H (F, B, D, A): passprint

This output (,) lets you know that Python will look at class H first, then B, D, A, and finally C.

Magic method

The Python class provides many "magic methods" that allow you to overload operators, treat class instances as iterators, and so on.

Magic methods are just like normal methods, but with the format _ _ method_name__ of a specific name. You already know a magic way, _ _ init__. Another example is the _ _ add__ magic method for overloading the + operator:

Class Vector: def _ init__ (self, x, y): self.x = x self.y = y def _ add__ (self, other): return Vector (self.x + other.x, self.y + other.y) v1 = Vector (3,2) v2 = Vector (4,1) v3 = v1 + v2

The _ _ iter__ and _ _ next__ magic methods enable you to iterate in the instance. This method returns the next iterative value or throws a StopIteration to indicate the end.

Class Fibonacci: def _ init__ (self, n): self.prev = 1 self.prev_prev = 1 self.n = n self.i = 0 def _ iter__ (self): return self def _ next__ (self): self.i + = 1 if self.i = = self.n + 1: raise StopIteration if self.i

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report