After reading this article , But for Python Linguistic characteristics 、 Have a certain understanding of coding style , And can write simple Python Program .
Of each system Python Please refer to the installation tutorial by yourself , No more details here .
Check Python edition , Enter at the command line python
that will do , At the same time, it will enter the command line interaction mode , You can perform... Here python command .
If... Is installed in the computer python2.x and python3.x Two versions , Input python
Running 2.x edition . Want to run 3.x, You need to enter python3
.
Enter at the command line python
:
Solo-mac:~ solo$ python Python 2.7.10 (default, Aug 17 2018, 19:45:58) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
Enter at the command line python3
:
Solo-mac:~ solo$ python3 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
Input exit()
You can exit command line mode .
If you have written a python file , Want to run it from the command line , Enter this directory , Enter at the command line python file name .py
that will do .
For example, there is a file on the desktop hello.py
, The content is to print a sentence :
print("Hello, Python")
Want to run it , Enter the first Desktop Catalog , Then enter... On the command line python hello.py
You can run :
Solo-mac:Desktop solo$ python hello.py Hello, Python
Variable names should be lowercase , Although there is no mandatory provision , But the rules commonly known as agreement .
A string is a series of characters . stay Python in , It's all strings in quotation marks , The quotation marks can be single quotation marks , Or double quotes , It can also be used at the same time . Such as :
"This is a string." 'This is also a string.' "I love 'python'"
The following describes the simple operation of string .
title() Show each word in uppercase , Change the initial of each word to uppercase .
>>> name = 'solo coder' >>> name.title() 'Solo Coder'
Change the string to all uppercase or all lowercase .
>>> name 'solo coder' >>> name.upper() 'SOLO CODER' >>> name.lower() 'solo coder' >>> name 'solo coder'
Be careful :title()、upper()、lower() Does not change the original string , Just output a new string .
Python Use the plus sign (+) To merge strings .
>>> first = 'solo' >>> last = 'coder' >>> full = first + ' ' + last >>> full 'solo coder'
In programming , White space refers to any nonprinting character , Such as space 、 Tabs and line breaks .
To add tabs to a string , Character combinations can be used \t
, To add a newline character to a string , Character combinations can be used \n
.
>>> print('\tPython') Python >>> print('Hello,\nPython') Hello, Python
rstrip()
Remove right margin ,lstrip()
Delete the left margin ,strip()
Delete the blanks at both ends .
>>> msg = ' Python ' >>> msg ' Python ' >>> msg.rstrip() ' Python' >>> msg.lstrip() 'Python ' >>> msg.strip() 'Python' >>> msg ' Python '
Note that after executing the space removal command , And print it out msg, Or the original string , This explanation strip()
It doesn't change the original string .
stay Python 2 in ,print The syntax of the statement is slightly different :
>>> python2.7 >>> print "Hello Python 2.7 world!" Hello Python 2.7 world!
stay Python 2 in , There is no need to put the content to be printed in parentheses . Technically speaking ,Python 3 Medium print It's a function , So brackets are essential . There are some Python 2 print Statements also contain parentheses , But its behavior is related to Python 3 Slightly different . In short , stay Python 2 In the code , There are some print Statement contains parentheses , Some do not contain .
stay Python in , You can add integers (+) reduce (-) ride (*) except (/) operation .
>>> 2 + 3 5 >>> 3 - 2 1 >>> 2 * 3 6 >>> 3 / 2 1.5
Python It also supports the order of operations , So you can use multiple operations in the same expression . You can also use parentheses to fix Change the operation order , Give Way Python Perform operations in the order you specify , As shown below :
>>> 2 + 3*4 14 >>> (2 + 3) * 4 20
Python All numbers with decimal points are called floating point numbers . Most programming languages use this term , It points out the fact that : The decimal point can appear anywhere in the number .
To a large extent , When you use floating-point numbers, you don't have to think about their behavior . You just type in the numbers you want to use ,Python They are usually handled the way you want them to be :
>>> 0.1 + 0.1 0.2 >>> 0.2 + 0.2 9 0.4 >>>2 * 0.1 0.2 >>>2 * 0.2 0.4
But it should be noted that , The number of decimal places contained in the result may be uncertain :
>>> 0.2 + 0.1 0.30000000000000004 >>> 3 * 0.1 0.30000000000000004
All languages have this problem , There is nothing to worry about .Python Will try to find a way , To represent the results as accurately as possible , But because of the way numbers are represented inside computers , It's hard in some cases . We'll learn more about how to deal with it later .
If you splice numbers with strings , There will be a type error . To avoid this problem , have access to str()
Convert a number to a string and then operate .
>>> age = 18 >>> print('my age is ' + age) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> print('my age is ' + str(age)) my age is 18
stay Python 2 in , Dividing two integers gives slightly different results :
>>> python2.7 >>> 3 / 2 1
Python The result returned is 1, instead of 1.5. stay Python 2 in , The result of integer division contains only the integer part , The decimal part Points deleted . Please note that , When calculating integer results , The approach taken is not to round , Instead, delete the decimal part directly .
stay Python 2 in , To avoid this , Make sure that at least one of the operands is a floating-point number , The result will also be Floating point numbers :
>>> 3 / 2 1 >>> 3.0 / 2 1.5 >>> 3 / 2.0 1.5 >>> 3.0 / 2.0 1.5
from Python 3 Switch to Python 2 Or from Python 2 Switch to Python 3 when , This division behavior is often confusing . When using or writing code that uses both floating-point numbers and integers , We must pay attention to this abnormal behavior .
stay Python in , Pound mark for annotation (#) identification . The contents after the well number will be changed Python The interpreter ignores . Such as
# Say hello to everyone print("Hello Python people!")
A list consists of a series of elements arranged in a specific order .
stay Python in , In square brackets ([]) To represent a list , And use commas to separate the elements .
>>> list = [] >>> list.append('haha') >>> list.append('heihei') >>> list.append('hehe') >>> list ['haha', 'heihei', 'hehe'] >>> list[0] 'haha'
To get the last element, you can use -1, Such as list[-1] Is to get the last element ,list[-2] Is to get the penultimate element .
Modify the element directly with the index
>>> list[0] = 'nihao' >>> list ['nihao', 'heihei', 'hehe']
You can add... At the end , You can also insert... Anywhere .
Add... At the end :append
>>> list.append('wa') >>> list ['nihao', 'heihei', 'hehe', 'wa']
Insert :insert
>>> list.insert(1, 'hello') >>> list ['nihao', 'hello', 'heihei', 'hehe', 'wa']
There are three ways to delete :
>>> list ['nihao', 'hello', 'heihei', 'hehe', 'wa'] >>> del list[1] >>> list ['nihao', 'heihei', 'hehe', 'wa'] >>> list.pop() 'wa' >>> list.remove('hehe') >>> list ['nihao', 'heihei']
to pop()
Pass the index to delete values in other locations
>>> list ['nihao', 'heihei'] >>> list.pop(0) 'nihao' >>> list ['heihei']
Be careful : Method remove() Delete only the first specified value . If the value to be deleted may appear more than once in the list , You need to use a loop to determine if all of these values have been deleted . If you're not sure you should use del Statement or pop() Method , Here's a simple criterion : If you want to remove an element from the list , And no longer use it in any way , Just use del sentence ; If you're going to be able to use it after deleting the element , Just use the method pop().
This section describes the sorting of lists 、 reverse 、 Calculate the length and other operations .
There are two main ways to sort lists :
Use sort()
Method will change the original list . If you want to reverse the sort , Just to sort() Method pass parameter reverse=True.
>>> list ['zhangsan', 'lisi', 'bob', 'alex'] >>> list.sort() >>> list ['alex', 'bob', 'lisi', 'zhangsan'] >>> list.sort(reverse=True) >>> list ['zhangsan', 'lisi', 'bob', 'alex']
function sorted()
Allows you to display list elements in a specific order , It doesn't affect their original order in the list .
If you want to reverse the sort , Just to sorted()
Pass parameters reverse=True.
>>> list = ['douglas','alex','solo','super'] >>> sorted(list) ['alex', 'douglas', 'solo', 'super'] >>> list ['douglas', 'alex', 'solo', 'super'] >>> sorted(list, reverse=True) ['super', 'solo', 'douglas', 'alex'] >>> list ['douglas', 'alex', 'solo', 'super']
To reverse the order of the list elements , Serviceable method reverse()
. reverse()
The original list will also be changed .
reverse()
It will only reverse the original order , No additional alphabetical sorting .
>>> list ['douglas', 'alex', 'solo', 'super'] >>> list.reverse() >>> list ['super', 'solo', 'alex', 'douglas']
Using functions len() You can quickly learn the length of the list .
>>> list ['super', 'solo', 'alex', 'douglas'] >>> len(list) 4
Use for…in
loop .
python Indent to distinguish code blocks , So you need to indent correctly
>>> cats ['super', 'solo', 'alex', 'douglas'] >>> for cat in cats: ... print(cat) ... super solo alex douglas
Python function range() It allows you to easily generate a series of numbers .
>>> for value in range(1,5): ... print(value) ... 1 2 3 4
Be careful :range() A series of values containing the first parameter but not the second parameter will be generated .
Use range()
Create a list of
>>> numbers = list(range(1,6)) >>> numbers [1, 2, 3, 4, 5]
range()
You can also specify steps . The following example generated from 0 Start , To 11 An even number of :
>>> nums = list(range(0,11,2)) >>> nums [0, 2, 4, 6, 8, 10]
There are several dedicated to dealing with lists of numbers Python function .
>>> numbers [1, 2, 3, 4, 5] >>> min(numbers) 1 >>> max(numbers) 5 >>> sum(numbers) 15
List parsing will for The loop and the code that creates the new element merge into a single line , And automatically attach new elements .
>>> squares = [value**2 for value in range(1,11)] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
To use this grammar , First, a descriptive list , Such as squares; then , Specify an open bracket , And define an expression , Used to generate the values you want to store in the list . In this example , Expression for value ** 2, It means Calculate the square value . Next , Write a for loop , Used to provide a value to an expression , Add the right square bracket . In this example , for The cycle is for value in range(1,11), It will be worth 1~10 To the expression value ** 2. Please note that , there for There is no colon at the end of the statement .
To create slices , You can specify the index of the first and last element to be used . And functions range() equally ,Python Stop after reaching the element before the second index you specify . To output the first three elements in the list , Need to specify index 0~3, This will output 0、1 and 2 The elements of .
>>> names = ['aa','bb','cc','dd'] >>> print(names[1:4]) ['bb', 'cc', 'dd']
If you don't specify the first index ,Python Will automatically start at the beginning of the list :
>>> print(names[:4]) ['aa', 'bb', 'cc', 'dd']
If no termination index is specified , Automatically get to the end of the list
>>> print(names[2:]) ['cc', 'dd']
You can also use negative index , For example, return the last three elements
>>> print(names[-3:]) ['bb', 'cc', 'dd']
Traversing slices
>>> for name in names[1:3]: ... print(name) ... bb cc
You can use slices to quickly copy lists , Do not specify start index and end index .
>>> names ['aa', 'bb', 'cc', 'dd'] >>> names2 = names[:] >>> names2 ['aa', 'bb', 'cc', 'dd']
A new list copied out of slices , It's a completely different list from the original list , Changing one doesn't actually affect the other list .
>>> names.append('ee') >>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> names2 ['aa', 'bb', 'cc', 'dd']
And if you simply assign a value, it will names Assign a value to names2, You can't get two lists , In fact, they all point to the same list . If you change one of them , The other will also be changed .
>>> names ['aa', 'bb', 'cc', 'dd'] >>> names2 = names >>> names2 ['aa', 'bb', 'cc', 'dd'] >>> names.append('ee') >>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> names2 ['aa', 'bb', 'cc', 'dd', 'ee']
Python A value that cannot be modified is called immutable , And immutable lists are called tuples .
Tuples look like lists , But use parentheses instead of square brackets to identify . After defining tuples , You can use the index to access its elements , It's like accessing list elements .
>>> food = ('apple', 'orange') >>> food[0] 'apple' >>> food[1] 'orange' >>> food[1] = 'banana' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
The traversal usage is consistent with the list .
Every one of them if The core of the statement is a value of True or False The expression of , This expression is called a conditional test .
==
!=
>
、 <
、 >=
、 <=
and
or
in
>>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> 'bb' in names Trueordinary if-else
>>> a = 10 >>> if a > 10: ... print('hello') ... else: ... print('bye') ... bye
if-elif-else
>>> if a<5: ... print(a<5) ... elif 5<a<10: ... print('5<a<10') ... else: ... print('a>10') ... a>10
stay Python in , A dictionary is a series of keys - It's worth it . Each key is associated with a value , You can use the key to access the value associated with it . The value associated with the key can be a number 、 character string 、 Lists and even dictionaries . in fact , Any Python Object is used as a value in the dictionary .
stay Python in , The dictionary is in curly brackets {} A series of keys in - Value pairs indicate .
>>> user = {'name':'bob', 'sex':'male', 'age':20} >>> user {'name': 'bob', 'sex': 'male', 'age': 20}
To get the value associated with the key , You can specify the dictionary name and the key in brackets .
>>> user {'name': 'bob', 'sex': 'male', 'age': 20} >>> user['name'] 'bob' >>> user['age'] 20
A dictionary is a dynamic structure , You can add keys to it at any time — It's worth it .
>>> user['city']='beijing' >>> user {'name': 'bob', 'sex': 'male', 'age': 20, 'city': 'beijing'}
To change the value in the dictionary , You can specify the dictionary name in turn 、 The key enclosed in square brackets and the new value associated with that key .
>>> cat = {} >>> cat['color'] = 'white' >>> cat['age'] = 4 >>> cat {'color': 'white', 'age': 4} >>> cat['age'] = 6 >>> cat {'color': 'white', 'age': 6}
For information no longer needed in the dictionary , You can use del Statement will correspond to the key — Delete value pairs completely . Use del When the sentence is , You must specify the dictionary name and the key to delete .
>>> del cat['color'] >>> cat {'age': 6}
Dictionaries can be used to store information in various ways , So there are many ways to traverse the dictionary : It can traverse all the keys in the dictionary — It's worth it 、 Key or value .
items()
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing'} >>> for k,v in cat.items(): ... print(k + '-' + str(v)) ... age-6 color-white city-beijing
adopt for k,v in cat.items()
Traverse all key value pairs in the same way ,k
Representative Key ,v
Representative value .
Be careful : Even when traversing the dictionary , key — The return order of value pairs is also different from the storage order .Python Don't care about keys — The order in which value pairs are stored , It only tracks the relationship between the key and the value .
keys()
If you don't need a value , It can be used keys()
Traverse all the keys .
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing'} >>> for k in cat.keys(): ... print(k.title()) ... Age Color City
The above example is printed out cat
All keys for , With string title()
Method to capitalize the first letter of each word .
When traversing the dictionary, all keys will be traversed by default ,for k in cat.keys()
and for k in cat
The effect is the same .
Traverse all keys in order , You can use sorted()
Sort , This makes Python List all the keys in the dictionary , And sort the list before traversing .
>>> for k in sorted(cat.keys()): ... print(k.title()) ... Age City Color
values()
>>> for value in cat.values(): ... print(str(value)) ... 6 white beijing
Eliminate duplicates if necessary , have access to set()
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing', 'city2': 'beijing'} >>> for value in cat.values(): ... print(str(value)) ... 6 white beijing beijing >>> for value in set(cat.values()): ... print(str(value)) ... beijing white 6
You can nest dictionaries in a list 、 Nesting lists in dictionaries and nesting dictionaries in dictionaries . I'm not going to do that here .
function input() Pause the program , Wait for the user to enter some text . After getting user input ,Python Store it in a variable , For your convenience .
>>> msg = input('Please input your name: ') Please input your name: solo >>> msg 'solo'
If you're using Python 2.7, The function... Should be used raw_input() To prompt the user for input . This function is associated with Python 3 Medium input() equally , Also interpret the input as a string .
Python 2.7 Also contains functions input(), But it interprets user input as Python Code , And try to run them . If you're using Python 2.7, Please use raw_input() instead of input() To get input .
If you want to convert the input into numbers , It can be used int()
To convert .
for The loop is used to create a code block for each element in the collection , and while The cycle goes on and on , Until the specified conditions are not met .
>>> num = 1 >>> while num <= 5: ... print(str(num)) ... num += 1 ... 1 2 3 4 5
To quit immediately while loop , No longer run the rest of the code in the loop , And regardless of the results of the conditional tests , You can use break sentence .break Statement is used to control the program flow , You can use it to control which lines of code execute , Which lines of code are not executed , This allows the program to execute the code you want to execute according to your requirements .
To return to the beginning of the loop , And according to the result of condition test, decide whether to continue to execute the loop , You can use continue sentence , It is not like break Statement to stop executing the rest of the code and exit the loop .
Python With keywords def
To define a function , The function name is given with a colon :
ending , The contents of the indent after the colon are the function body .
>>> def greet(): ... print('Hello World!') ... >>> greet() Hello World!
You can pass arguments to a function . The following example is a directional function greet()
Passed an argument name
. among name
It's a parameter ,solo
Is the argument .
>>> def greet(name): ... print('Hello,' + name) ... >>> greet('solo') Hello,solo
There are many ways to pass arguments to functions , You can use positional arguments , This requires the order of arguments to be the same as the order of formal parameters ; You can also use keyword arguments , Its Each argument in the consists of a variable name and a value ; You can also use lists and dictionaries .
When you call a function ,Python Each argument in a function call must be associated with a parameter in the function definition . So , The simplest way to relate is based on the order of arguments . This association is called positional argument .
>>> def student(name, age): ... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old') ... >>> student('solo', 18) Hello, My name is solo, I am 18 years old
Arguments passed in the order defined by formal parameters are called positional arguments .
The keyword argument is the name passed to the function — It's worth it . Keyword arguments allow you to ignore the order of arguments in a function call , It also clearly points out the purpose of each value in the function call .
>>> student(age=18, name='solo') Hello, My name is solo, I am 18 years old
Next, the example in the location argument ,student(name, age)
The first parameter of the method is name
, The second parameter is age
. We use keyword arguments to indicate which one is passed , Even if the order is written out of order, the result will not be out of order .
When you write a function , You can specify a default value for each parameter . When an argument is provided to a formal parameter in the calling function ,Python The specified argument value will be used ; otherwise , The default value of the formal parameter will be used . therefore , After a parameter is assigned a default value , You can omit the corresponding arguments in the function call . Use default values to simplify function calls , The typical usage of functions can also be clearly pointed out .
>>> def student(name, age=18): ... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old') ... >>> student('bob') Hello, My name is bob, I am 18 years old >>> student('nicole') Hello, My name is nicole, I am 18 years old >>> student('bob', 20) Hello, My name is bob, I am 20 years old
Above , to student()
The second parameter of the function definition age
Set the default value 18
, If only one parameter is passed when calling , Whatever it is age
All are 18. When passing two parameters , The arguments passed will override the default value .
Be careful : When using default values , In the formal parameter list, the formal parameter without default value must be listed first , Then list the arguments with default values . This makes Python Still able to correctly interpret location arguments .
Functions do not always display output directly , contrary , It can process some data , And return one or a set of values . The function returns The value of is called the return value . In the function , You can use return Statement to return the value to the line of code that called the function . The return value allows you to move most of the heavy work of the program into functions , So as to simplify the main program .
>>> def student(name): ... return name ... >>> name = student('solo') >>> name 'solo'
Function can return any type of value , Including more complex data structures such as lists and dictionaries . for example , The following function accepts name and age , And return a dictionary of people :
>>> def build_person(name,age): ... person = {'name':name, 'age':age} ... return person ... >>> p = build_person('solo',18) >>> p {'name': 'solo', 'age': 18}
occasionally , You don't know in advance how many arguments a function needs to take , Fortunately Python Allows functions to collect any number of arguments from the calling statement .
>>> def person(*args): ... print(args) ... >>> person('name','age','address') ('name', 'age', 'address')
A function is defined above person()
, There is only one parameter *args
. The name of the parameter *args
The asterisk in makes Python Create a file called args
Empty tuples of , And encapsulates all the values received in the tuple .
If you want a function to accept different types of arguments , Formal parameters that accept any number of arguments must be placed last in the function definition .Python First match location arguments and keyword arguments , Then collect the remaining arguments into the last parameter .
>>> def person(city, *args): ... print('city: ' + city + ', other args:') ... for value in args: ... print(value) ... >>> person('beijing', 'name', 'age', 'tel') city: beijing, other args: name age tel
function person()
There are two parameters , first city
Is an ordinary positional argument , the second *args
It's a variable parameter .
occasionally , You need to accept any number of arguments , But I don't know in advance what information will be passed to the function . under these circumstances , Functions can be written to accept any number of keys — It's worth it —— Accept as much as the call statement provides . One such example is to create a user profile : You know you will receive information about users , But I'm not sure what kind of information it will be .
def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key,value in user_info.items(): profile[key] = value return profile user = build_profile('steven', 'bob', city='beijing', age=18) print(user)
Execute code , The output is :
{'first_name': 'steven', 'last_name': 'bob', 'city': 'beijing', 'age': 18}
Functions can be stored in a separate file called a module , Then import the module into the main program .import Statement allows the code in the module to be used in the currently running program file .
The module has the extension .py The file of , Contains the code to be imported into the program .
cat.py
def eat(food): print('I am cat, I eat ' + food)
animal.py
import cat cat.eat('fish')
Console output
I am cat, I eat fish
You can also import specific functions in the module , The syntax of this import method is as follows :
from module_name import function_name
By separating function names with commas , You can import any number of functions from the module as needed :
from module_name import function_0, function_1, function_2
The above example only imports cat.py
Medium eat()
Method
from cat import eat eat('fish')
Get the same result .
If the name of the function to be imported may conflict with an existing name in the program , Or the name of the function is too long , You can specify a short and unique alias —— Another name for the function , It's like a nickname . To assign this special nickname to a function , You need to do this when importing it .
from cat import eat as cat_eat cat_eat('fish')
take cat.py
Medium eat()
Method imports and specifies an alias cat_eat
, When using, you can use alias directly .
You can also give the module an alias . By giving the module a short alias , Let you It is easier to call functions in modules .
General grammar :import module_name as mn
import cat as c c.eat('fish')
Use the asterisk (*) The operator allows Python Import all functions in the module :
cat.py
def eat(food): print('I am cat, I eat ' + food) def run(): print('cat run')
animal.py
from cat import * eat('fish') run()
Output results
I am cat, I eat fish cat run
Because of importing Each function , Each function can be called by name , Instead of using a period representation . However , Use not written by yourself Large modules , It's best not to use this import method : If the name of a function in the module matches the name used in your project Same as , May lead to unexpected results : Python You may encounter multiple functions or variables with the same name , And then cover the function , and Not all functions are imported separately .
The best thing to do is , Or just import the functions you need to use , Either import the whole module and use the period notation . It can Make the code clearer , Easier to read and understand .
class Cat(): def __init__(self, name, color): self.name = name self.color = color def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') my_cat = Cat('Spring', 'white') print(my_cat.name) print(my_cat.color) my_cat.eat() my_cat.run()
The class created above Cat
, And instantiated my_cat
, Then the class method is called. eat()
and run()
. Output results :
Spring white cat Spring color white, now eat cat Spring color white, now run
A function in a class is called a method .__init__()
Is the construction method of function , When a new instance is created in each file Python Will run it automatically . Note that the constructor name must be this , It's prescribed .
In the example above __init__(self, name, color)
There are three formal parameters , First parameter self
essential , It must also precede the other parameters . Other parameters can be adjusted as needed .self
Is a reference to the instance itself , Gives instances access to properties and methods in the class .
You can also access properties directly through instances :my_cat.name
. This is not recommended in other languages .
stay Python 2.7 When creating a class in , Minor modifications are needed —— Include the word... In parentheses object:
class ClassName(object):
Each attribute in a class must have an initial value , Even if the value is 0 Or empty string . In some cases , For example, when setting the default value , In the method __init__()
It is possible to specify this initial value in ; If you do this for an attribute , You don't need to include a formal parameter that provides an initial value for it .
Redefinition Cat
, Attribute in construction method age
Set the default value .
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age))
The value of an attribute can be modified in three different ways : Modify directly through the instance , Set by method .
To modify the value of the property , The easiest way is to access it directly through an instance .
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age)) my_cat = Cat('Spring', 'white') my_cat.print_age() my_cat.age = 4 my_cat.print_age()
The output is
cat`s age is 3 cat`s age is 4
The above example goes directly through my_cat.age = 4
Revised age
The value of the property .
Then update the code , Join in update_age()
Method to modify age
Properties of .
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age)) def update_age(self, age): self.age = age my_cat = Cat('Spring', 'white') my_cat.print_age() my_cat.update_age(10) my_cat.print_age()
Run code output :
cat`s age is 3 cat`s age is 10
When one class inherits another , It automatically gets all the properties and methods of another class ; The original class is called the parent class , The new class is called a subclass . A subclass inherits all the properties and methods of its parent class , You can also define your own properties and methods .
class Animal(): def __init__(self, name, age): self.name = name self.age = age def run(self): print('Animal ' + self.name + ' run') class Cat(Animal): def __init__(self, name, age): super().__init__(name, age) cat = Cat('Tony', 2) cat.run()
Run the program , Output :
Animal Tony run
First define the class Animal
, It also defines Cat
Inherited from Animal
. Animal
Called the parent class , Cat
Called subclass . Through the output, you can verify , The subclass inherits the method of the parent class .
In the construction method of subclass, the construction method of parent class must be implemented first :super().__init__(name, age)
.
You can also define your own methods for subclasses , Or override the method of the parent class .
class Animal(): def __init__(self, name, age): self.name = name self.age = age def run(self): print('Animal ' + self.name + ' run') class Cat(Animal): def __init__(self, name, age): super().__init__(name, age) def play(self): print('Cat ' + self.name + ' play') def run(self): print('Cat ' + self.name + ' run') cat = Cat('Tony', 2) cat.run() cat.play()
Let's change the program ,Animal
Class invariant ,Cat
Class still inherits Animal
, But he defined his own method play()
And rewrites the parent class method run()
. Run the program , Get the output :
Cat Tony run Cat Tony play
stay Python 2.7 in , Inheritance syntax is slightly different ,ElectricCar The definition of class is similar to the following :
class Car(object): def __init__(self, make, model, year): --snip-- class ElectricCar(Car): def __init__(self, make, model, year): super(ElectricCar, self).__init__(make, model, year) --snip--
function super() Two arguments are required : Subclass name and object self. To help Python Associate a parent class with a subclass , These arguments are essential . in addition , stay Python 2.7 When using inheritance in , Be sure to specify... In parentheses when defining the parent class object.
When a file is too long , You can pull some of the code out , Then import it into the main file .
There are many ways to import :
car.py
Class is defined in Car
from car import Carcar.py
It contains three classes Car
, Battery
and ElectricCar
. Import only one class : from car import ElectricCar Import multiple classes , The middle is separated by commas : from car import Car, ElectricCarTo use the information in a text file , First of all, you need to read the information into memory . So , You can read the entire contents of the file at once , It can also be read step by step, one line at a time .
with open('test.txt') as file_obj: contents = file_obj.read() print(contents)
open()
Used to open a file , Parameter is the path of the file .
keyword with
Close the file after you no longer need to access it . With with
You just open the file , And use it when you need it ,Python Self meeting Automatically turn it off when appropriate .
Compared to the original file , The only difference in this output is that there is an empty line at the end . Why is there such an empty line ? because read()
An empty string is returned when the end of the file is reached , When the empty string is displayed, it is a blank line . To delete extra empty lines , Can be found in print Use in statement rstrip()
.
The file path can be a relative path , It could be an absolute path .
with open('test.txt') as file_obj: for line in file_obj: print(line.rstrip())
Check the file one line at a time , You can use for loop .
with open('test.txt', 'w') as file_obj: file_obj.write("I love python")
In this example , call open() Two arguments are provided when , The first argument is also the name of the file to open ; The second argument ('w') tell Python, We're going to open this file in write mode .
Optional mode :
r
: read-only .w
: Just write . If the file does not exist, create , If the file exists, empty it first , Write again .a
: Additional mode , The written content is appended to the original file . If the file does not exist, create .r+
: Can read but write .If you omit the pattern arguments ,Python The file will be opened in the default read-only mode .
Exceptions are used try-except Code block processing .try-except Block of code to Python Performs the specified operation , At the same time to tell Python What happens when something unusual happens .
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") else: print("no exception")
If try
The code in ran successfully , No exception occurred , execute else
Code in a code block .
Python Use in json.dump()
and json.load()
To store and read json file .
import json userInfo = {'username': 'jack', 'age': 18} with open('test.txt', 'w') as obj: json.dump(userInfo, obj) with open('test.txt') as obj: content = json.load(obj) print(content)
In the example above json.dump()
Put the data in test.txt
in , And with json.load()
Take the data out of the file and print .
Please import before use json modular .
First define a function to splice names name_function.py
def get_formatted_name(first, last): full_name = first + ' ' + last return full_name.title()
Then write a test class to test this function
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): def test_name_function(self): full_name = get_formatted_name('david', 'alex') self.assertEqual(full_name, 'David Alex') unittest.main()
Test class to inherit unittest.TestCase
, adopt self.assertEqual
Assert whether the result is the same as expected .
Method
purpose
assertEqual(a, b)
verify a == b
assertNotEqual(a, b)
verify a != b
assertTrue(x)
verify x by True
assertFalse(x)
verify x by False
assertIn(item, list)
verify item stay list in
assertNotIn(item, list)
verify item be not in list in
setUp()
Method If you are in the TestCase Class contains methods setUp()
,Python Will run it first , Then run each to test_ The way to start .
Usually used to do some initialization operations .
pyton Its language characteristics and coding style are relatively easy to understand , It's also the foundation , This article is just a preliminary study python A cushion for , You should learn how to use it well , It's also a process and a good start .
In this paper, from https://juejin.cn/post/6844903765410070535, If there is any infringement , Please contact to delete .