According to Liao Xuefeng python3 tutorial----python study 12th Day

Source: Internet
Author: User
Tags first string


Using modules

Python itself contains many very useful modules that can be used immediately as soon as the installation is complete.

Our built-in sys module, for example, writes a Hello module:

' A test module ' # A string represents a document comment, and the first string of any module code is treated as a document comment of the module __author__= ' xiaoming ' #作者名 can be deleted above or not import sys    #导入 SYS module DEF test (): args = sys.argv if Len (args) ==1:print (' hello,world! ') Elif len (args) ==2:print (' hello,%s '%args[1]) else:print ("Too many argumments!") if __name__ = = ' __main__ ': Test ()


The SYS module has a argv variable that stores all the parameters of the command with the list. argv at least one element to you as the first parameter is always the name of the. py file, for example:

Run

E:\python>python lianxi.py obtained sys.argv is [' lianxi.py ']

Run

E:\python>python lianxi.py Mingtian obtained the sys. ARGV is [' lianxi.py ', ' Mingtian ']

Finally, notice the two lines of code:

If __name__== ' __main__ ': Test ()


When we run the Lianxi module file at the command line, the Python interpreter puts a special variable __name__ to __main__, and if the Lianxi module is imported elsewhere, the if pre-section fails, so the IF Testing allows a module to run an extra code from the command line, most commonly by running tests.

Run lianxi.py with the command number:

E:\python>python lianxi.pyhello,world!
E:\python>python lianxi.py Mingtianhello,mingtian


Start the python interactive environment, and then import the practice module:

>>> import lianxi>>> lianxi.test () hello,world!


The import did not print Hello,world because there is nothing to do with the test () function. The test () function is called to print Hello,world


Scope

In a module, we may define many functions and variables, worrying about functions and variables we want to use for others, and some functions and variables that we want to use only within the module. In Python, this is done through the _ prefix.

Normal functions and variable names are public and can be consumed directly, for example: ABC,X123,PI, etc.:

A function or variable similar to __xxx__ should be non-public (private) and should not be consumed directly, such as _ABC,__ABC, etc.:

We say that private functions and variables should not be consumed directly, not "cannot" be consumed directly, because Python does not have a way to completely restrict access to private functions or variables, but it is not customary to apply private functions or variables.


Private functions or variables should not be referenced by others, what is the use of them? :

def _private_1 (name): Return ' Hello,%s '%namedef _private_2 (name): Return ' Hi,%s '%name def greeting (na Me): If Len (name) > 3:return _private_1 (name) Else:return _private_2 (name)


We expose the function in the module and greeting() hide the internal logic with the private function, so that the calling greeting() function does not care about the internal private function details, which is also a very useful way to encapsulate and abstract the code, namely:


Functions that do not need to be referenced externally are all defined as private, and only functions that need to be referenced externally are defined as public.


Object-Oriented Programming

OO programming------Object oriented programming, or OOP, is a programming idea. OOP takes objects as the basic unit of a program, and an object contains functions for data and manipulating data.

Process-oriented programming treats a computer program as a set of commands, and a sequence of functions. In order to simplify the program design, the process will continue to cut the function into a molecular function, that is, the large function by cutting into a small block function to reduce the complexity of the decency.

Object-oriented programming treats computer programs as a set of objects, and each object can accept messages from other objects and process them, and the execution of a computer program is a series of messages passing between objects.

In Python, all data types can be treated as objects and, of course, objects can be customized. The custom data type is the concept of class classes in object-oriented.


Eg: Shows a student's score

(1) Process oriented:

>>> std1 = {' name ': ' Micheal ', ' score ':98}>>> std2 = {' name ': ' Bob ', ' score ':81}>>> def Print_ Score (STD): print ('%s:%s '% (std[' name '],std[' score '))


>>> Print_score (STD1) micheal:98>>> Print_score (STD2) bob:81


(2) Using object-oriented program design idea, we prefer not to think about the program's execution flow, but student this data type should be treated as an object that has both name and score properties. To print a student's sentence, the prime Minister must create an object for the student, and then send a Print_score message to the object to print out his own data.

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))


Sending a message to an object is actually a call to the object's corresponding associated function, which we call the object method. The object-oriented program is written like this:

>>> bart = Student (' Bart ', ' a ') >>> Lisa = Student (' Lisa ', 98) >>> Bart.print_score () bart:59 >>> Lisa.print_score () lisa:98


Classes and instances

Object-oriented concepts are classes (class) and instances (Instance), and it is important to keep in mind that classes are abstract templates, such as student classes, and instances are specific "objects" that are created from classes, each with the same method, but the data may be different for each object.

In Python, the definition of a class is by class keyword:

>>> class Student (object): Pass


classfollowed by the class name, that is, the Student class name is usually the beginning of the word in uppercase, followed by (object) , indicating which class is inherited from the class,

In general, if there is no suitable inheriting class, use the object class, which is the class that all classes will eventually inherit.


Once you have defined the Student class, you can Student create Student an instance from the class by using the class name + () to create the instance:

>>> bart = Student (' xiaoming ', $) >>> bart<__main__. Student object at 0x02ceaa70>>>> student<class ' __main__. Student ' >



As you can see, the variable is bart pointing to an Student instance, followed by a 0x10a67a590 memory address, each object has a different address, and Student itself is a class.


You are free to bind attributes to an instance variable, for example, to bart bind an instance to an name attribute:

>>> bart.name = ' xaioming ' >>> bart.name ' xaioming '



Because a class can act as a template, you can force a number of attributes that we think must be bound to be filled in when creating an instance. By defining a special __init__ method, when you create an instance, you bind the name score attributes, such as:

Class Student (object): Def __init__ (self,name,score): Self.name = name Self . score = Score


Note that the first argument of the __init__ method is always self, which means that the created instance itself, so within the __init__ method, you can bind the various properties to self, because the individual points to the created instance itself. With the __inlt__ method when creating an instance, you cannot pass in an empty argument, you must pass in a parameter that matches the __init__ method, but self does not need to be passed, and the Python interpreter will put the instance variable in itself:

>>> bart = Student (' xiaoming ', $) >>> bart.name ' xiaoming ' >>> bart.score66


A function defined in a class is only a bit different than a normal function, which is that the first argument is always the instance variable self and, when called, does not pass the argument. In addition, there is no difference between a class method and a normal function, so you can use default, variable, keyword, and named keyword parameters


Data encapsulation

An important feature of object-oriented programming is data encapsulation. In the student class above, each instance has its own name and score the data.

We can access this data through functions, such as printing a student's score:

def print_score (self): print ('%s:%s '% (Self.name,self.score))
>>> def print_score (STD): print ('%s:%s '% (Std.name, Std.score))


>>> Print_score (Bart) Bart simpson:59



Since the student instance itself has this data, there is no need to access the data from outside functions, you can directly define the functions that access the data within the student class, so that the ' data ' is encapsulated. The functions of these encapsulated data are associated with the student class itself, which we call the class method:

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)) >>> Bart=stud ENT (' xiaoming ', Bart.print_score) >>> () xiaoming:99


Access restrictions

Inside class, you can have properties and methods, and external code can manipulate the data by invoking the instance variable directly, thus hiding the complex logic inside.


However, from the definition of the previous student class, the external code is free to modify the Name,score property of an instance:

>>> bart=student (' Bart ', 98) >>> bart.score98>>> bart.score=59>>> bart.score59



If you want to make an internal property, you can put the name of the property with two underscore __, in Python, the variable name of the instance starts with __, it becomes a private variable (private), only the internal can be accessed, external cannot access, so we change the student class:

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))      def  get_grade (self):                if self.score>=90:                     return  ' A '                 elif self.score>=60:                     return  ' B '                 else:                     return  ' C '

After the change, for external code, there is no change, but it has been unable to access from outside 实例变量.__name and 实例变量.__score :

>>> bart=student (' Bart ', 98) >>> Bart.__name Traceback (most recent call last): File "<pyshell#11> ; ", line 1, in <module> bart.__nameattributeerror: ' Student ' object have no attribute ' __name '

This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection.

But what if external code gets 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 to self. __score


What if I want to allow external code to modify score? You can add additional methods to the student class set_score :

Class Student (object): ... def set_score (self, score): Self.__score = Score

In the method, you can check the parameters to avoid passing in invalid arguments:

Class Student (object): ... def set_score (self, score): If 0 <= score <= 100: Self.__score = score else:raise valueerror (' Bad score ')




It is important to note that in Python, the variable name is similar, which starts with a double underscore, and ends with a double underscore, which is a special variable that __xxx__ can be accessed directly, not a private variable, so __name__ __score__ the variable name cannot be used.


Sometimes we see an instance variable name that starts with an underscore, such as an _name instance variable that can be accessed externally, but, as you see in the rules, when you look at a variable like this, the meaning is, "although I can be accessed, please treat me as a private variable and don't feel free to access it."


is an instance variable that starts with a double underscore not necessarily externally accessible? Actually, it's not. cannot be accessed directly __name because the Python interpreter has changed the variable to the outside __name _Student__name , so you can still _Student__name access the __name variable by:

>>> bart._student__name ' Bart Simpson '




Because different versions of the Python interpreter may change to __name different variable names.

All in all, Python itself has no mechanism to stop you from doing bad things, all on your own.





This article is from the "Creative Pilgrim" blog, so be sure to keep this source http://dearch.blog.51cto.com/10423918/1762873

According to Liao Xuefeng python3 tutorial----python study 12th Day

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.