Introduction to basic learning of Python

零下一度
Release: 2017-07-19 23:47:44
Original
1284 people have browsed it

In Python, names with the first letter in capital letters refer to classes. The brackets in this class definition are empty because we are creating this class from blank space. We wrote a docstring describing the functionality of this class. Functions in a class are called methods.

Taking the Student class as an example, in Python, defining a class is through the class keyword:

class Student(object) :

Pass

Class is followed by the class name, namely Student. The class name is usually a word starting with a capital letter, followed by ( object), indicating which class the class inherits from. Usually, if there is no suitable inheritance class, the object class is used. This is the class that all classes will eventually inherit.

9.1.1 Create class

 2. Each method call associated with a class automatically passes the actual parameter self, which is a reference to the instance itself, allowing the instance to access the properties and methods in the class. self is passed automatically, so we don't need to pass it.

class Student(object):

def __init__( self, name, score):

                                                                                                                                                                                                                                  __init__() is a special method that Python automatically runs whenever a new instance is created. There are two underscores

at the beginning and end. This is a convention designed to avoid name conflicts between Python default methods and ordinary methods. In the definition of this method, the

formal parameter self is essential and must be located

before other formal parameters.
 3. Variables prefixed with self are available to all methods in the class, and we can also access these variables through any instance of the class.

 4.self.name= name Variables like this that can be accessed through instances are called attributes 5. An important feature of object-oriented programming is data encapsulation. You can directly define functions for accessing data inside the class, thus encapsulating the "data". These functions that encapsulate data

are associated with the Student class itself, which we call methods of the class.

9.1.2 Create an instance based on the class

We usually You can think of a name with the first letter in uppercase (such as Dog) as referring to the class, while a lowercase name (such as my_dog) refers to the instance created from the class.

 1. To access the attributes of the instance, you can use the

period notation. We wrote the following code to access the value of the attribute name of my_dog.

My_dog.name

The period notation is very commonly used in Python. This syntax demonstrates how Python learns the value of an attribute.

 2. After creating an instance based on the Dog class, you can use period notation to call any method defined in the Dog class.

 3. Any number of instances can be created based on the class as needed.

9.2 Using classes and instances

1. An important task you need to perform is to modify the properties of the instance. You can modify the properties of an instance directly, or you can write methods to modify them in a specific way.

 2. A class is a template for creating an instance, and an instance is a specific object. The data owned by each instance is independent of each other and does not affect each other; the method is the function bound to the instance, and the ordinary function Differently, methods can directly access the data of the instance; by calling the method on the instance, we directly operate the data inside the object, but there is no need to know the implementation details inside the method. Unlike static languages, Python allows any data to be bound to instance variables. That is to say, for two instance variables, although they are different instances of the same class, they may have different variable names.

9.2.1 Set an initial value for the class

Every attribute in the class must have an initial value, even if the value is 0 or an empty string. In some cases, such as when setting a default value, it is possible to specify such an initial value within the __init__() method; if you do this for an attribute, you do not need to include formal parameters that provide it with an initial value.

Define attributes directly in class, which are class attributes:

class Student(object):

name = 'Student'

When writing a program, never use the same name for instance attributes and class attributes, because instance attributes with the same name will block the class attributes, but when you delete the instance attributes, use the same name again to access What arrives will be the class attributes.

9.2.2 Modify the value of the attribute

You can modify the value of the attribute in three different ways:

1. Modify directly through the instance;

 2. Set through methods;

 3. Increment through methods (increase a specific value).

9.2.3 Access restrictions

1. Inside a Class, there can be properties and methods, and external code can manipulate data by directly calling the instance variable method, thus hiding the internal complex logic.

2. If you want to prevent internal attributes from being accessed externally, you can add two underscores __ before the name of the attribute. In Python, if the variable name of the instance starts with __, it becomes A private variable (private) can only be accessed internally and not externally.

class Student(object):

def __init__(self, name, score):

self.__name = name

# Self .__ SCORE = Score

DEF PRINT_SCORE (SELF):

Print (' %s: %s' %(seld .__ name , self.__score))

3. After the change, there are no changes to the external code, but the instance variables .__name and .__name are no longer accessible from the outside. Instance variable .__score:

##>>> bart = Student('Bart Simpson', 98)

>> ;> bart.__name

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'Student' object has no attribute '__name'

 4. This ensures that external code cannot modify the internal state of the object at will, thus protecting it through access restrictions , the code is more robust. But if external code wants to obtain name and score, you can add methods like get_name and get_score to the Student class:

class Student(object):

...

def get_name(self):

return self.__name

def get_score(self):

            return self.__score

5. If you want to allow external code to modify the score, you can add the set_score method to the Student class:

class Student(object):

...

def set_score(self, score):

self.__score = score

 6. Compared with the original direct call parameters, in the method, the parameters can be checked to avoid passing in invalid parameters:

##class Student(object):

...

def set_score(self, score):

if 1

##

7. It should be noted that in Python, variable names are similar to __xxx__, that is, starting with a double underscore and ending with a double underscore, they are special variables. Special variables can be accessed directly and are not private. variables, so variable names such as __name__ and __score__ cannot be used. Sometimes, you will see instance variable names starting with an underscore, such as _name. Such instance variables can be accessed externally. However, according to the convention, when you see such a variable, it means That is, "Although I can be accessed, please treat me as a private variable and do not access it at will."

 8. Instance variables starting with a double underscore are not necessarily inaccessible from the outside. The reason why __name cannot be accessed directly is that the Python interpreter externally changes the __name variable to _Student__name, so the __name variable can still be accessed through _Student__name.

9.3 Inheritance

 1. If a class is similar to a special version of another class, you can use inheritance. If a class inherits another class, it will automatically obtain all the properties and methods of the other class. The original class is the parent class, and the new class is the child class.

 2. The subclass inherits all the attributes and methods of the parent class, and can also define its own attributes and methods. In OOP programming, when we define a class, it can inherit from an existing class. The new class is called a subclass (Subclass), and the inherited class is called a base class, parent class or super class. (Base class, Super class).

class Dog(Animal): #Inherit Animal

pass

9.3.1 Subclass method __init__()

1. Inheritance requires assigning values ​​to all attributes of the parent class, and the __init__() of the subclass requires help from the parent class.

 2. And the parent class must be in the inheritance file, before the child class.

 3. When defining a subclass, the name of the parent class must be specified in parentheses.

 4.super() special function helps Python connect parent classes and subclasses in parallel. The parent class is also called the super class, the origin of super.

9.3.2 Define methods and attributes of subclasses

Let a class inherit from another class. Properties and methods that distinguish subclasses from parent classes can be added.

9.3.3 Rewriting the parent class

Methods corresponding to the parent class can be rewritten only if they do not meet the needs of the subclass. Add new methods to the subclass to describe the characteristics of the subclass. . Get rid of the worst of the parent category and take the best.

9.3.4 Polymorphism

1. When the same method exists in both the subclass and the parent class, we say that the subclass overrides the method of the parent class. When the code is running, Subclass methods are always called. In this way, we gain another benefit of inheritance: polymorphism

 2. Therefore, in the inheritance relationship, if the data type of an instance is a subclass, its data type can also be regarded as Is the parent class. However, the reverse is not true.

3. The advantage of polymorphism is that when we need to pass in Dog, Cat, Tortoise..., we only need to receive the Animal type, because Dog, Cat, Tortoise... are all Animal types , and then just operate according to the Animal type. Since the Animal type has a run() method, any type passed in, as long as it is an Animal class or subclass, will automatically call the run() method of the actual type. This is what polymorphism means.

 4. For a variable, we only need to know that it is of Animal type, without knowing exactly its subtype, we can safely call the run() method, and the specific run() method called is the function Whether on an Animal, Dog, Cat or Tortoise object is determined by the exact type of the object at runtime. This is the real power of polymorphism: the caller only cares about the call, regardless of the details, and when we add a new subclass of Animal, Just make sure the run() method is written correctly, regardless of how the original code is called. This is the famous "open and closed" principle:

  • Open for extension: new Animal subclasses are allowed;

  • Closed for modification: not Functions such as run_twice() that depend on Animal type need to be modified.

9.3.5 Using __slots__

In order to achieve the purpose of restriction, Python allows you to define a special __slots__ variable when defining a class to limit the Attributes that can be added to class instances.

class Student(object):

__slots__ = ('name', 'age') # Use tuple to define attributes that are allowed to be bound name

When using __slots__, please note that the attributes defined by __slots__ only affect the current class instance and have no effect on inherited subclasses.

9.3.6 Multiple inheritance

1. Through multiple inheritance, a subclass can obtain all the functions of multiple parent classes at the same time.

 2. When designing the inheritance relationship of a class, usually the main line is inherited from a single source. For example, Ostrich inherits from Bird. However, if you need to "mix in" additional functionality, you can achieve it through multiple inheritance. For example, let Ostrich inherit Runnable in addition to inheriting from Bird. This design is often called MixIn. The purpose of MixIn is to add multiple functions to a class. In this way, when designing a class, we give priority to combining multiple MixIn functions through multiple inheritance instead of designing multi-level complex inheritance relationships.

 3. In this way, we do not need a complicated and huge inheritance chain. As long as we choose to combine the functions of different classes, we can quickly construct the required subclasses. Since Python allows multiple inheritance, MixIn is a common design. Languages ​​that only allow single inheritance (such as Java) cannot use MixIn's design.

9.3.7 Customized classes

1. There are many special-purpose functions in Python classes that can help us customize classes.

__str__

After defining the __str__() method, you can return a nice-looking string:

##> >> class Student(object):

... def __init__(self, name):

... self.name = name

... def __str__(self):

...                 return 'Student object (name: %s)' % self.name

...

>>> ; print(Student('Michael'))

Student object (name: Michael)

The example printed out in this way not only looks good, And it is easy to see the important data inside the instance.

If you type variables directly without printing, the printed example still doesn’t look good:

##>>> s = Student('Michael ') This is Because the direct display variable call is not __str__(), but __repr__(). The difference between the two is that __str__() returns the string seen by the user, while __repr__() returns the string seen by the program developer. , that is to say, __repr__() is for debugging.

>>> s

<__main__.Student object at 0x109afb310>

The solution is to define another __repr__(). But usually the codes of __str__() and __repr__() are the same, so there is a lazy way to write it:

##class Student(object):__iter__
def __init__(self, name):

self.name = name

def __str__(self):

return 'Student object (name=% s)' % self.name

__repr__ = __str__

If a class wants to be used for . .. in loop, like list or tuple, must implement an __iter__() method, which returns an iterable object. Then, Python's for loop will continuously call the __next__() method of the iterative object to get the loop. the next value until the loop exits when a StopIteration error is encountered.

We take the Fibonacci sequence as an example and write a Fib class that can be used in the for loop:

class Fib(object) : Now, try to apply the Fib instance to the for loop:
def __init__(self):

self.a, self.b = 0, 1 # Initialize two counters a, b

def __iter__(self):

Return self # The instance itself is the iteration object, so return self

def __next__(self):

self.a , self.b = self.b, self.a + self.b # Calculate the next value

if self.a > 100000: # Conditions for exiting the loop

raise StopIteration()

         return self.a # Return the next value

##>>> for n in Fib():...        print(n)

...

1

1

2

3

5

...

46368

75025

__getitem__

Although the Fib instance can be used in for loops and looks a bit like a list, it is still not possible to use it as a list. For example, take the 5th element:

## To behave like a list In order to extract elements according to the subscript, you need to implement the __getitem__() method:
##>>> Fib()[5]

Traceback (most recent call last):

File "

TypeError: 'Fib' object does not support indexing

##class Fib(object):__getattr__
def __getitem__(self, n):

a, b = 1, 1

for x in range(n):

a, b = b, a + b

return a

Python has another mechanism, which is to write a __getattr__() method to dynamically return an attribute. When calling a non-existent attribute, such as score, the Python interpreter will try to call __getattr__(self, 'score') to try to obtain the attribute, so that we have the opportunity to return the value of score. Existing attributes, such as name, will not be looked up in __getattr__.

__call__

 1. Any class only needs to define a __call__() method to directly call the instance.

 2. Through the callable() function, we can determine whether an object is a "callable" object.

9.3.8 Enumeration class

Define a class type for such an enumeration type, and then each constant is a unique instance of the class. Python provides the Enum class to implement this function:

from enum import Enum

9.3.9 Metaclass

type()

To create a class object, the type() function passes in 3 parameters in sequence:

  1. class name;

  2. A collection of inherited parent classes. Note that Python supports multiple inheritance. If there is only one parent class, don’t forget the single-element writing method of tuple;

    ## The method name of
  3. #class is bound to the function. Here we bind the function fn to the method name hello.

metaclass

Metaclass, literally translated as metaclass, the simple explanation is: after we define a class, we can create an instance based on this class, so: first Define the class and then create instances. But what if we want to create a class? Then you must create a class based on metaclass, so: define metaclass first, and then create the class. The connection is: first define metaclass, then you can create the class, and finally create the instance. The parameters received by the

__new__() method are:

  1. The object of the class currently being created;

  2. class The name; the collection of parent classes inherited by the

  3. class; the collection of methods of the

  4. class.

9.3.10 Using instances as properties

When you use code to simulate real objects, as you add more and more features and details, you will find properties and methods And the code files are getting longer and longer. At this time, part of them can be separated and reorganized into a class. A large category can be divided into many subcategories.

9.3.11 Simulating physical objects

To simulate more complex physical objects, you need to consider it from a higher logical level. In order to write more efficient, concise and accurate code, you may need to constantly reorganize classes.

9.4 Importing classes

 1. As classes continue to be added, even excellent inheritance will make the code very long, so python allows you to import classes into modules. And import the required modules for use in the main program.

 2. Write a documentation string for each of your modules, explain the function of the module, and briefly describe the content.

 3. Import multiple classes from a module, separate them with commas, and create instances according to your own needs.

 4. You can also import the entire class, add the class name before the instance, and access the required class.

 5. Import one module into another module.

9.5 python standard library (module)

The Python standard library is a set of modules that can be imported and used with only the import statement.

Dictionaries allow you to associate information, but do not record the order in which you add key-value pairs. To create a dictionary and record the order in which you add key-value pairs, you can use the orderedDict class in the collections module. Instances of OrderedDict are the same as dictionaries, but record the order in which key-value pairs are added.

OrderdDict is very good. It has the characteristics of both a list and a dictionary, which is sometimes needed.

random module

Contains functions for generating random numbers in various ways. Where randint() returns an integer within the specified range.

datetime is a module

The datetime module also contains a datetime class. The datetime class is imported through from datetime import datetime. If you are importing only import datetime, you must quote the full name datetime.datetime.

datetime.now() returns the current date and time, its type is datetime.

Commonly used third-party libraries

There are also MySQL drivers: mysql-connector-python, NumPy library for scientific computing: numpy, template tool Jinja2 for generating text, etc. .

 1.urlparse module, the urlpasrse module provides some basic functions for processing URL strings. These functions include urlparse(), urlunparse(), and urljoin().

 2.urlparse() parses urlstr into a 6-tuple (prot_sch, net_loc, path, params, query, frag). Each component here has been described previously.

 3. The function of urlunparse() is completely opposite to that of urlpase(). It generates the urltup 6-tuple (prot_sch, net_loc, path, params, query, frag) from the URL processed by urlparse(), and splices it into a URL and returns.

 4. The urllib module provides many functions that can be used to download data from a specified URL. It can also encode and decode strings so that they can be displayed in the correct form in the URL. The functions to be introduced below include urlopen(), urlretrieve(), quote(), unquote(), quote_plus(), unquote_plus(), and urlencode().

 5.urlopen() opens a Web connection represented by a given URL string and returns an object of file type.

 6.urlretrieve() is not used to access and open the URL in the form of a file, but to download the complete HTML and save it as a file.

9.6 Class Coding Style

Be familiar with the coding style related to classes, especially when the program is complex.

 1. Class names should use

camel case, that is, the first letter of the class is capitalized, without underscores, while the first letter of the instance name and module name is lowercase, and underscores are used to connect words.

 2. Add a documentation string description after each class definition to briefly describe the function of the class, and add a documentation string description under each module to describe what the classes under the module can do. A brief description.

 3. Use blank lines to organize code, but do not abuse it. You can use one blank line to separate methods in a class, and use two blank lines to separate classes.

 4. When you need to import modules in the standard library and modules written by yourself at the same time, first write the import statement to import the standard library module, separated by a blank line, and then import the module import statement written by yourself. When multiple import statements are included, it is easier to understand the origin of each module in the program.

Month = Enum('Month', ('Jan' , 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

The above is the detailed content of Introduction to basic learning of Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!