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

Related concepts of python class

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

Share

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

This article introduces the relevant knowledge of "related concepts of python class". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

What are classes, objects, instances, class # # title variables (class attributes), instance variables (instance properties)

Classification of class variables and class attributes

Class calls the instance method

Class enclosure, inheritance and polymorphism

Iterations, iterators (iterator), iteratable objects (iterable object), generators (generator)

What are classes, objects, instances, class # # title variables (class attributes), instance variables (instance properties)

Object-oriented programming (Object-oriented Programming, referred to as OOP) is a method of encapsulating code. For example, throwing messy data into the list is a simple encapsulation, a data-level encapsulation; packaging commonly used blocks of code into a function, which is also a kind of encapsulation, is a statement-level encapsulation. Object-oriented programming is also an idea of encapsulation, which encapsulates the data describing features and code blocks (functions) together.

In object-oriented, common terms include classes, objects, properties, and methods:

Class: understandably a template through which numerous concrete instances (also known as objects) can be created.

Objects (instances): classes cannot be used directly, only instances created by the class can be used.

Attributes: all variables in a class are called properties.

Methods: all functions in a class are often called methods. However, unlike all functions, class methods must contain at least one self parameter. Class methods cannot be used alone and can only be used with objects of the class.

Classification of class variables and class attributes

Neither class properties nor class methods can use them directly outside the class as ordinary variables or functions do. We can think of the class as an independent space, then the class attribute is actually the variable defined in the class body, and the class method is the function defined in the class body.

In the class body, class attributes can be subdivided into the following three types, depending on where the variable is defined and how it is defined:

In the class body, outside all functions: variables defined in this scope are called class attributes or class variables

In the body of a class, inside all functions: variables defined as "self. Variable names", called instance properties or instance variables

In the body of the class, within all functions: variables defined in the way "variable name = variable value" are called local variables.

Like class attributes, class methods can be divided into class methods, instance methods, and static methods. In actual programming, class methods and static methods are rarely used, because we can use functions instead of them to achieve the desired functions, but in some special scenarios (such as factory mode), using class methods and static methods is also a good choice.

Different from the classification of class attributes:

Class methods: methods modified by @ classmethod

Static method: using @ staticmethod > modified method

Example method: without any modification

Constructor: when creating a class, we can manually add an init () method, which is a special class instance method called a constructor (or constructor). The constructor is used when creating an object, and the Python interpreter automatically calls it whenever an instance object of a class is created.

Class calls the instance method

In fact, there are two ways to call the instance method, either using the class object or directly through the class name.

Class CLanguage: # the following defines two class variables name = "python language" add = "http://c.biancheng.net.python" # _ _ init__ is the constructor It also belongs to the instance method def _ init__ (self,name,add): # the following defines two instance variables self.name = name self.add = add print (name, "URL:", add) # below defines a say instance method def say (self, content): print (content) # below defines a count instance method def count (self Money): # defines a local variable sale sale = 0.8*money print ("the price after the discount is:", sale) # defines a class method @ classmethod def info (cls): print ("calling class method", cls) # defines a static method @ staticmethod def info (name,add): print (name) Add) # assign the CLanguage object to the clanguage variable # call the instance method # CLanguage.say directly through the class name ("call the instance method directly through the class name") will report an error You must manually pass the clang class object to the self parameter clang = CLanguage ("C language Chinese net 1", "the parameter passed by http://c.biancheng.net")# should be the same as init's CLanguage.say (clang," call the instance method directly through the class name ") # directly call the instance method clang2 = CLanguage (" C language Chinese net 2 ") through the class object "http://c.biancheng.net")clang2.say(" calls instance method directly through class object") # output C language Chinese method 1 URL is: http://c.biancheng.net directly calls instance method C language Chinese Web 2 URL is: http://c.biancheng.net directly calls instance method class encapsulation (enclosure) through class object Inheritance and polymorphism

1. Encapsulation

Simply understand Encapsulation, that is, when designing a class, deliberately hide some properties and methods inside the class, so that when using this class, you will not be able to directly call these properties (or methods) in the form of "class object. Property name" (or "class object. Method name (parameter)"), but can only use unhidden class methods to manipulate these hidden properties and methods indirectly.

How is the Python class encapsulated?

Unlike other object-oriented programming languages such as C++ and Java, variables and functions in the Python class are either public (similar to public properties) or private (similar to private). The differences between the two properties are as follows:

Public: class variables and class functions of public attributes, which can be accessed normally on the outside of the class, inside the class, and in subclasses (more on inheritance later).

Private: class variables and class functions for private attributes can only be used within this class, but not outside the class or subclasses.

Python does not provide modifiers such as public and private. To implement class encapsulation, Python takes the following approach:

By default, variables and methods in the Python class are public, and their names are not preceded by an underscore (_)

If the name of a variable and function in a class begins with a double underscore "" but does not end with a double underscore "", the variable (function) is a private variable (private function) and its property is equivalent to

Private .

Refer to the details of the package

two。 Inheritance and polymorphism

In OOP (Object Oriented Programming) programming, when we define a class, we can inherit from an existing class, the new class is called a subclass (Subclass), and the inherited class is called a base class, a parent class or a superclass (Base class, Super class).

What are the benefits of inheritance? The biggest benefit is that the subclass gets all the attributes and functions of the parent class.

Using class subclass_name (baseclass_name) to represent inheritance

Class Person (object): def _ init__ (self,name,sex): self.name = name self.sex = sex def print_title (self): if self.sex = = "male": print ("man") elif self.sex = = "female": print ("woman") class Child (Person): # Child inherits Person passMay = Child ("May") "female") Peter = Person ("Peter", "male") print (May.name,May.sex,Peter.name,Peter.sex) # subclass inherits parent method and attribute May.print_title () Peter.print_title () # output May female Peter malewomanman

Isinstance () and issubclass ()

Python differs from other languages in that when we define a class, we actually define a data type. The data types we define are no different from those that come with Python, such as str, list, and dict.

Python has two functions to determine inheritance: isinstance () to check the instance type and issubclass () to check class inheritance. See the following example:

Class Person (object): passclass Child (Person): # Child inheritance Person passMay = Child () Peter = Person () print (isinstance (May,Child)) # Trueprint (isinstance (May,Person)) # Trueprint (isinstance (Peter,Child)) # Falseprint (isinstance (Peter,Person)) # Trueprint (issubclass (Child,Person)) # True

Before explaining what polymorphism is, we override the print_title () method in the Child class: if male,print boy;, if female,print girl

Class Person (object): def _ _ init__ (self,name Sex): self.name = name self.sex = sex def print_title (self): if self.sex = = "male": print ("man") elif self.sex = = "female": print ("woman") class Child (Person): # Child inherits Person def print_title (self): if self.sex = = "male": Print ("boy") elif self.sex = = "female": print ("girl") May = Child ("May") "female" Peter = Person ("Peter", "male") print (May.name,May.sex,Peter.name,Peter.sex) May.print_title () Peter.print_title ()

When both the subclass and the parent class have the same print_title () method, the print_title () of the subclass overrides the print_title () of the parent class, and when the code runs, the print_title () of the subclass is called.

In this way, we get another benefit of inheritance: polymorphism.

The advantage of polymorphism is that when we need to pass in more subclasses, such as adding Teenagers, Grownups, and so on, we only need to inherit the Person type, while the print_title () method can be either directly overridden (that is, using Person) or a unique one. That's what polymorphism means. The caller just calls, regardless of the details, and when we add a subclass of Person, we just make sure that the new method is written correctly, regardless of the original code. This is the famous principle of "opening and closing":

Open to extension (Open for extension): allows subclasses to rewrite method functions to modify closed (Closed for modification): do not rewrite, directly inherit parent method functions

Subclass override constructor

The subclass may not have a constructor, which means that the constructor is the same as the parent class; the subclass can also override the constructor. Now, we need to add two attribute variables to the subclass Child: mother and father, which can be constructed as follows (it is recommended that the subclass call the constructor of the parent class, see the following code):

Class Person (object): def _ _ init__ (self,name,sex): self.name = name self.sex = sexclass Child (Person): # Child inherits Person def _ _ init__ (self,name,sex,mother,father): Person.__init__ (self,name Sex) # calls to the constructor of the parent class self.mother = mother self.father = fatherMay = Child ("May", "female", "April", "June") print (May.name,May.sex,May.mother,May.father)

Multiple inheritance

The concept of multiple inheritance should be easy to understand. For example, you need to create a new class baby inheritance Child, which can inherit the properties and methods of the parent class and the upper class of the parent class, and give priority to using the near methods of the layer class. The code is as follows:

Class Person (object): def _ init__ (self,name,sex): self.name = name self.sex = sex def print_title (self): if self.sex = = "male": print ("man") elif self.sex = = "female": print ("woman") class Child (Person): passclass Baby (Child): passMay = Baby ("May") "female") # inherits the property print (May.name) of the upper parent class May.sex) # May femaleMay.print_title () # woman can use the parent method class Child (Person): def print_title (self): if self.sex = = "male": print ("boy") elif self.sex = = "female": print ("girl") class Baby (Child): passMay = Baby ("May") "female") May.print_title () # girl gives priority to using the method iteration of the upper class Iterator (iterator), iterable object (iterable object), generator (generator)

Iteration: is a way to access collection elements. Given a list or tuple, we can traverse the list or tuple through a for loop, which we call Iteration.

Iterative object: if the _ _ iter__ method is defined in the class and an iterator object is returned, the created object is called an iterable object.

Strings, lists, meta-ancestors, dictionaries, collections, and so on, are all iterable objects.

(no _ _ next__)

If you can iterate over an object, you can use a for loop

# Strings, lists, meta-ancestors, dictionaries, collections, etc., are all iterable objects for i in [1,2,3]: print (I) obj = {"a": 123," b ": 456} for k in obj: print (k)

Create an iterable object

Class foo (object): def _ iter__ (self): return iterator object (generator object) obj = foo () # obj is an iterable object # create iterator class IT (object): def _ init__ (self): self.counter = 0 def _ iter__ (self): return self Def _ _ next__ (self): self.counter + = 1 if self.counter = = 3: raise StopIteration () # create iterator object class foo (object): def _ iter__ (self): return IT () obj = foo () # obj is an iterable object for item in obj: # Loop iterable object Internally, execute obj.__iter__ () and get the iterator object, and then continue to execute the _ _ next__ method print (item) of the iterator object.

Iterator: an iterator is an object that remembers the location of the traversal

_ _ iter__ and _ _ next__ methods are defined in the class

_ _ iter__ returns the object itself, namely self

_ _ next__ returns the next data, or if not, a stopiteration exception.

The iterator object is accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward, not backward.

Iterators have two basic methods (built-in functions): iter () and next (); the built-in function iter () converts iterable objects into iterators. Read the next element one by one through the next () method

Create an iterator

There are three ways to create an iterator:

Convert an iterable object to an iterator through the python built-in function iter ()

Create an iterator to satisfy the two methods defined in class (1): _ _ iter__ and _ _ next__. (2) _ _ next__ returns the next data. If not, it returns two conditions with an exception of stopiteration >.

Created by generator (generator)

# method 1: iter () converts an iterable object into an iterator list= [1,2,3,4] it = iter (list) # create an iterator object # use next () to traverse the data print (next (it)) # 1print (next (it)) # traverse the data using the for loop, because of the simplicity of the for loop, it is more common for the # for loop to execute the iter of the iterator and get the returned object Execute next (object) for x in it: print (x, end= ") # 3 4print (next (it)) # StopIteration# method 2: create an iterator class MyNumbers: def _ iter__ (self): self.a = 1 return self def _ next__ (self): if self.a

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