Introduction to Python Basic learning

Source: Internet
Author: User
Tags uppercase letter
In Python, the name of an uppercase letter refers to a class. The parentheses in this class definition are empty, because we want to create this class from whitespace. We have written a document string describing the functionality of this class. A function in a class is called a method.

Take the student class as an example, in Python, the definition class is through the Class keyword:

Class Student (object):

Pass

The class name, student, is usually preceded by a class name, followed by (object), indicating which class the class inherits from, and generally, if there is no suitable inheriting class, the object class is used, which is the class that all classes eventually inherit.

9.1.1 Creating a Class

Class Student (object):

def __init__ (self, Name, score):

Self.name = Name

Self.score = Score

1. Method __init__ () is a special method that Python will run automatically when a new instance is created. There are two underscores at the beginning and the end, which is a convention designed to avoid naming conflicts between Python's default methods and normal methods. In the definition of this method, the formal parameter self is necessary and must precede the other parameters.

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

3. Variables prefixed with self can be used by all methods in the class, and we can access them through any instance of the class.

4.self.name= name a variable that can be accessed through an instance is called a property

5. An important feature of object-oriented programming is data encapsulation. Functions that access the data can be defined directly within the class, so that the "data" is encapsulated. The functions of these encapsulated data are associated with the student class itself, which we call the method of the class.

9.1.2 to create an instance from a class

We can usually assume that the name of the initial capitalization (such as dog) refers to a class, whereas a lowercase name (such as My_dog) refers to an instance created from a class.

1, to access the properties of the instance, you can use the period notation , we have written the following code to access the value of the My_dog property name.

My_dog.name

The period notation is commonly used in Python, which demonstrates how Python learns the value of a property.

2. After creating an instance from the dog class, you can use the period notation to invoke any method defined in the dog class.

3. You can create as many instances as you want based on your class.

9.2 Using classes and instances

1. One 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 a method to modify it in a specific way.

2. The class is the template that creates the instance, and the instance is a concrete object, each instance has data that is independent of each other, the method is the function that binds to the instance, and the ordinary function is different, the method can directly access the data of the instance, by invoking the method on the instance, we manipulate the data inside the object directly. But there is no need to know the implementation details inside the method. Unlike static languages, Python allows you to bind any data to an instance variable, which means that for two instance variables, although they are different instances of the same class, the variable names you have may be different.

9.2.1 setting an initial value for a class

Each property in the class must have an initial value, even if the value is 0 or an empty string. In some cases, it is possible to specify this initial value in method __init__ () when setting a default value, and if you do so for a property, you do not need to include the formal parameter that provides the initial value for it.

The attribute is defined directly in class, which is the class property:

Class Student (object):

name = ' Student '

When writing a program, never use the same name for instance properties and class properties, because instance properties of the same name will block out class attributes, but when you delete an instance property and then use the same name, the class attribute is accessed.

9.2.2 Modifying the value of a property

You can modify the value of a property in three different ways:

1. Modify directly through the example;

2. Set through the method;

3. Increment by method (increase a specific value).

9.2.3 Access Restrictions

1. Inside the class, there can be properties and methods, while external code can manipulate the data by invoking the instance variable directly, thus hiding the complex logic inside.

2. If you want the internal properties not to be accessed externally, you can add the name of the property with two underscores __, in Python, the variable name of the instance begins with __ and becomes a private variable (private) that can only be accessed internally and cannot be accessed externally.

Class Student (object):

def __init__ (self, Name, score):

Self.__name = Name

Self.__score = Score

def print_score (self):

Print ('%s:%s '% (Self.__name, Self.__score))

3. After the change, there is no change to the external code, but the instance variable cannot be accessed externally. __name and instance variables. __score:

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

>>> Bart.__name

Traceback (most recent):

File "<stdin>", line 1, in <module>

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

4. This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection. However, if external code is to get name and score, you can add methods such as 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 score again, you can add the Set_score method to the student class:

Class Student (object):

...

def set_score (self, score):

Self.__score = Score

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

Class Student (object):

...

def set_score (self, score):

If 0 <= score <= 100:

Self.__score = Score

Else

Raise ValueError (' Bad score ')

7. It is important to note that in Python, the variable name is similar to __xxx__, which starts with a double underscore and ends with a double underscore, which is a special variable that can be accessed directly, not as a private variable, so you cannot use __name__, __score__ Such a variable name. There are times when you see an instance variable name that starts with an underscore, such as _name, which can be accessed outside of an instance variable, but, as you see in the rules, when you look at such a variable, it means, "although I can be accessed, but please treat me as a private variable, do not arbitrarily access ”。

8. An instance variable that begins with a double underscore is also not necessarily inaccessible from outside. The __name cannot be accessed directly because the Python interpreter has changed the __name variable to _student__name, so the __name variable can still be accessed through _student__name.

9.3 Inheritance

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

2. Subclasses inherit all the properties and methods of the parent class, and can also define their own and methods. In OOP programming, when we define a class, we can inherit from an existing class, and the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base-Class, Super-Class).

Class Dog (Animal): #继承Animal

Pass

Methods of 9.3.1 subclasses __init__ ()

1. Inheritance needs to assign values to all the properties of the parent class, and the subclass's __init__ () requires a parent class to be a helping hand.

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

3. When defining a subclass, you must specify the name of the parent class in parentheses.

4.super () special function to help Python to parallel the parent class and subclass. The parent class is also called Super class, the origin of super.

9.3.2 defining methods and properties for subclasses

After you have a class that inherits a class. You can add properties and methods that distinguish between subclasses and parent classes.

9.3.3 overriding the parent class

The method corresponding to the parent class can be overridden only if it does not conform to the subclass, and a new method is added to the subclass to describe the characteristics of the subclass. Go to the father's to its worst fear to take its essence.

9.3.4 polymorphism

1. When both the subclass and the parent class have the same method, we say that the subclass overrides the method of the parent class and always calls the subclass's method when the code runs. In this way, we gain another benefit of inheritance: polymorphic

2. Therefore, in an inheritance relationship, if the data type of an instance is a subclass, its data type can also be considered a parent class. But, in turn, it doesn't work.

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 animal types, and then follow the animal type. Because the animal type has the run () method, any type passed in, as long as it is a animal class or subclass, will automatically invoke the actual type of the run () method, which is the meaning of polymorphism.

4. For a variable, we only need to know that it is a animal type, do not need to know exactly its subtype, you can safely call the run () method, and the specific call of the run () method is on the animal, Dog, cat or Tortoise object, Determined by the exact type of the object at run time, this is the real power of polymorphism: The caller just calls, regardless of the details, and when we add a animal subclass, simply make sure that the run () method is written correctly, regardless of how the original code is called. This is the famous "opening and shutting" principle:

    • Open to extensions: Allow new animal subclasses;

    • Closed for modification: You do not need to modify functions such as run_twice () that depend on the animal type.

9.3.5 using __slots__

For the purpose of limiting, Python allows you to define a special __slots__ variable when defining a class to limit the attributes that the class instance can add.

Class Student (object):

__slots__ = (' name ', ' age ') # defines the name of the property allowed to bind with a tuple

Use __slots__ Note that the properties defined by __slots__ only work on the current class instance and do not work with inherited subclasses.

9.3.6 Multiple Inheritance

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

2. When designing an inheritance relationship for a class, the main line is usually inherited from a single inheritance, for example, ostrich (ostrich) inherits from Bird. However, if you need to "mix in" additional functionality, it can be achieved through multiple inheritance, for example, to allow ostrich to 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, so that when designing a class, we prioritize the ability to combine multiple mixin with multiple inheritance, rather than designing complex, hierarchical inheritance relationships.

3. So that we do not need a complex and large succession chain, as long as the choice of combining the functions of different classes, you can quickly construct the desired subclass. Because Python allows multiple inheritance, mixin is a common design. Only single-inherited languages, such as Java, are allowed to use the mixin design.

9.3.7 Custom Class

There are many special purpose functions in the 1.Python class that can help us customize the class.

__str__

Define the __STR__ () method to 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)

This kind of printed example, not only good-looking, but also easy to see the important data inside the instance.

Directly knocking the variable without print, the printed instance is still not good to see:

>>> s = Student (' Michael ')

>>> s

<__main__. Student Object at 0x109afb310>

This is because the direct display of the variable calls is not __str__ (), but __repr__ (), the difference between the two is __str__ () returns the string that the user sees, and __repr__ () returns the string that the program developer sees, that is, __repr__ () is for debugging services.

The solution is to define a __repr__ () again. But usually the __str__ () and __repr__ () codes are the same, so there's a lazy way to do it:

Class Student (object):

def __init__ (self, name):

Self.name = Name

def __str__ (self):

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

__repr__ = __str__

__iter__

If a class wants to be used for the for ... in loop, like a list or tuple, you must implement a __iter__ () method that returns an iterative object, and then the python for loop constantly calls the iteration object's __next__ () The Stopiteration method gets the next value of the loop until it exits the loop when it encounters an error.

For the Fibonacci sequence, we write a fib class that can be used for a For loop:

Class Fib (object):

def __init__ (self):

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

def __iter__ (self):

The return self # instance itself is an iterative object, so return to its own

def __next__ (self):

SELF.A, self.b = self.b, SELF.A + self.b # calculates the next value

If SELF.A > 100000: # Exit the condition of the loop

Raise Stopiteration ()

Return SELF.A # returns the next value

Now, try acting on the For loop with the FIB instance:

>>> for N in Fib ():

... print (n)

...

1

1

2

3

5

...

46368

75025

__getitem__

Although the FIB instance can be used for a for loop, it looks a bit like the list, but using it as a list or not, for example, take the 5th element:

>>> Fib () [5]

Traceback (most recent):

File "<stdin>", line 1, in <module>

TypeError: ' Fib ' object does not support indexing

To act as a list to take out elements according to the subscript, you need to implement the __getitem__ () method:

Class Fib (object):

def __getitem__ (self, N):

A, B = 1, 1

For x in range (n):

A, B = B, A + b

Return a

__getattr__

Python also has another mechanism, which is to write a __getattr__ () method that dynamically returns an attribute. When a non-existent property is called, such as the Score,python interpreter tries to invoke __getattr__ (self, ' score ') to try to get the property, then we have the opportunity to return the value of score. Existing attributes, such as name, are not found in __getattr__.

__call__

1. In any class, only one __call__ () method needs to be defined to invoke the instance directly.

2. With 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 class. Python provides an enum class to implement this function:

from enum import enum

month = Enum (' Month ', (' Jan ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec '))

9.3.9 Yuan Class

Type ()

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

    1. The name of the class;

    2. Inherited parent class Collection, note that Python supports multiple inheritance, if there is only one parent class, do not forget the single element of tuple notation;

    3. Class's method name and function binding, where we bind the function fn to the method name hello.

Metaclass

Metaclass, literal translation is a meta-class, the simple explanation is: When we define the class, we can create an instance based on this class, so: First define the class, and then create the instance. But what if we want to create a class? Then you must create the class from Metaclass, so define the Metaclass first, and then create the class. The connection is: Define Metaclass First, you can create the class, and finally create the instance.

The parameters that are received by the __new__ () method are:

    1. The object of the class that is currently ready to be created;

    2. The name of the class;

    3. The collection of parent classes that the class inherits;

    4. The collection of methods for the class.

9.3.10 using instances as attributes

When you use code to simulate a physical object, when you add more and more features and details, you will find that the properties and methods as well as the code files are getting longer, which can be separated and re-formed into a class. You can divide a large class into many small classes.

9.3.11 Simulated physical

The simulation of more complex objects needs to be considered from a higher logical level. In order to write more efficient, more concise and accurate code, it may be necessary to constantly reorganize classes.

9.4 Importing Classes

1. With the constant addition of classes, even good inheritance can be very long code, so Python lets you import classes into modules. and import the required modules in the main program.

2. Write the document string for each module, explain the function of the module, and briefly describe the content.

3. Import multiple classes from a module, separate them with commas, and create an instance based on your own needs.

4. You can also import the entire class and precede the instance with the class name, and access the required classes.

5. Import another module in one module.

9.5python standard library (module)

The Python standard library is a set of modules that can be imported using only import statements.

Dictionaries let you associate information, but do not record the order in which you add key-value pairs, create dictionaries, and record the order in which you add key-value pairs, using the Ordereddict class in module collections. The Ordereddict instance is the same as the dictionary, but the order in which the added key-value pairs are added is recorded.

Orderddict is very good, both the list and dictionary features, and sometimes it is necessary.

Random module

A function that contains various ways to generate random numbers. where Randint () returns an integer that is within the specified range.

DateTime is a module

The DateTime module also contains a DateTime class, which is a datetime import through the From datetime import DateTime. If you import only the import datetime, you must refer to the full name Datetime.datetime.

DateTime.Now () returns the current date and time, whose type is DateTime.

Common third-party libraries

And the MySQL driver: Mysql-connector-python, the NumPy Library for Scientific Computing: NumPy, the template tool for generating text Jinja2, and so on.

1.urlparse module, the Urlpasrse module provides some basic functionality for handling URL strings. These features include Urlparse (), Urlunparse (), and Urljoin ().

2.urlparse () parses the urlstr into a 6-tuple (Prot_sch, net_loc, path, params, query, Frag). Each of these components is described earlier.

The function of 3.urlunparse () is in contrast to Urlpase (), which generates Urltup (Prot_sch, Net_loc, path, params, query, Frag) by Urlparse () processing URL, stitched into URL and return.

The 4.urllib module provides a number of functions that can be used to download data from a specified URL, as well as encode and decode the string so that it can be displayed in the correct form in the URL. The functions that will be described below include Urlopen (), Urlretrieve (), quote (), unquote (), Quote_plus (), Unquote_plus (), and UrlEncode ().

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

6.urlretrieve () is not used as a file to access and open the URL, but instead to download the full HTML, save as a file.

Class 9.6 Coding style

Familiarity with class-related coding styles is more appropriate when the program is complex.

1. The class name should be the hump naming method , that is, the first letter of the class, without an underscore, and the instance name and module first letter lowercase, and underline the word.

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

3. Use a blank line to organize your code, but do not misuse it by using a blank line separation method in the class, separating the class with two blank lines.

4. When you need to import both the module in the standard library and the module you write, write the import statement that imports the standard library module, separate it with a blank line, and import the module you have written. When you include multiple import statements, it makes it easy to understand the origins of each module in the program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.