Small Examples
1. Numbers
1. Absolute Value
Absolute value or modulus of a complex number
In [1]: abs(-6)
Out[1]: 6
2. Base Conversion
Convert decimal to binary:
In [2]: bin(10)
Out[2]: '0b1010'
Convert decimal to octal:
In [3]: oct(9)
Out[3]: '0o11'
Convert decimal to hexadecimal:
In [4]: hex(15)
Out[4]: '0xf'
3. Integer and ASCII Conversion
Decimal integer corresponding to ASCII character
In [1]: chr(65)
Out[1]: 'A'
Check the decimal number corresponding to a certain ASCII character
In [1]: ord('A')
Out[1]: 65
4. Check if All Elements are True
Returns True
if all elements are true, otherwise False
In [5]: all([1,0,3,6])
Out[5]: False
In [6]: all([1,2,3])
Out[6]: True
5. Check if At Least One Element is True
Returns True
if at least one element is true, otherwise False
In [7]: any([0,0,0,[]])
Out[7]: False
In [8]: any([0,0,1])
Out[8]: True
6. Determine Truth Value
Test whether an object is True
or False
.
In [9]: bool([0,0,0])
Out[9]: True
In [10]: bool([])
Out[10]: False
In [11]: bool([1,0,1])
Out[11]: True
7. Create Complex Number
Create a complex number
In [1]: complex(1,2)
Out[1]: (1+2j)
8. Get Quotient and Remainder
Get quotient and remainder respectively
In [1]: divmod(10,3)
Out[1]: (3, 1)
9. Convert to Float Type
Convert an integer or numeric string to a float
In [1]: float(3)
Out[1]: 3.0
If it cannot be converted to float, it will raise ValueError
:
In [2]: float('a')
# ValueError: could not convert string to float: 'a'
10. Convert to Integer
int(x, base=10)
, where x
can be a string or numeric, converts x
to a regular integer. If the parameter is a string, it may contain a sign and decimal point. If it exceeds the representation range of a regular integer, a long integer is returned.
In [1]: int('12',16)
Out[1]: 18
11. Power
Base raised to the power of exp, if mod is given, take the modulus
In [1]: pow(3, 2, 4)
Out[1]: 1
12. Rounding
Round off, ndigits
represents how many decimal places to keep:
In [11]: round(10.0222222, 3)
Out[11]: 10.022
In [12]: round(10.05,1)
Out[12]: 10.1
13. Chained Comparison
i = 3
print(1 < i < 3) # False
print(1 < i <= 3) # True
2. Strings
14 Convert String to Bytes
Convert string to byte type
In [12]: s = "apple"
In [13]: bytes(s,encoding='utf-8')
Out[13]: b'apple'
15 Convert Any Object to String
In [14]: i = 100
In [15]: str(i)
Out[15]: '100'
In [16]: str([])
Out[16]: '[]'
In [17]: str(tuple())
Out[17]: '()'
16 Execute Code Represented by String
Compile a string into code that Python can recognize or execute, and can also read text as a string and then compile it.
In [1]: s = "print('helloworld')"
In [2]: r = compile(s,"<string>", "exec")
In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
In [4]: exec(r)
helloworld
17 Calculate Expression
Treat the string str
as a valid expression to evaluate and return the calculation result extracted from the string content
In [1]: s = "1 + 3 +5"
...: eval(s)
...:
Out[1]: 9
18 String Formatting
Format output string, format(value, format_spec)
essentially calls the __format__(format_spec)
method of value
.
In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18
3.1415926 | {:.2f} | 3.14 | Keep two decimal places |
---|---|---|---|
3.1415926 | {:+.2f} | +3.14 | Keep two decimal places with sign |
-1 | {:+.2f} | -1.00 | Keep two decimal places with sign |
2.71828 | {:.0f} | 3 | No decimal |
5 | {:0>2d} | 05 | Number padded with zero (left fill, width 2) |
5 | {:x<4d} | 5xxx | Number padded with x (right fill, width 4) |
10 | {:x<4d} | 10xx | Number padded with x (right fill, width 4) |
1000000 | {:,} | 1,000,000 | Comma-separated number format |
0.25 | {:.2%} | 25.00% | Percentage format |
1000000000 | {:.2e} | 1.00e+09 | Scientific notation |
18 | {:>10d} | ‘ 18’ | Right align (default, width 10) |
18 | {:<10d} | ’18 ‘ | Left align (width 10) |
18 | {:^10d} | ‘ 18 ‘ | Center align (width 10) |
3. Functions
19 Built-in Sorting Function
Sorting:
In [1]: a = [1,4,2,3,1]
In [2]: sorted(a,reverse=True)
Out[2]: [4, 3, 2, 1, 1]
In [3]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'xiaohong','age':20,'gender':'female'}]
In [4]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[4]:
[{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]
20 Sum Function
Sum:
In [181]: a = [1,4,2,3,1]
In [182]: sum(a)
Out[182]: 11
In [185]: sum(a,10) # Initial value for sum is 10
Out[185]: 21
21 Nonlocal in Nested Functions
The keyword nonlocal
is often used in nested functions to declare the variable i
as a non-local variable; if not declared, i+=1
indicates that i
is a local variable within the function wrapper
, and since i+=1
references i
without declaration, it will raise an unreferenced variable
error.
def excepter(f):
i = 0
t1 = time.time()
def wrapper():
try:
f()
except Exception as e:
nonlocal i
i += 1
print(f'{e.args[0]}: {i}')
t2 = time.time()
if i == n:
print(f'spending time:{round(t2-t1,2)}')
return wrapper
22 Global Declaration of Global Variables
First, let’s answer why we need global
. A variable is referenced by multiple functions, and we want the global variable to be shared by all functions. Some may think this is simple, just write:
i = 5
def f():
print(i)
def g():
print(i)
pass
f()
g()
Both functions f
and g
can share the variable i
, and the program does not report an error, so they still do not understand why global
is needed.
However, if I want a function to increment i
, like this:
def h():
i += 1
h()
At this point, when executing the program, bang, an error occurs! It throws an exception: UnboundLocalError
, because the compiler interprets i+=1
as a local variable within the function h()
, and clearly, the compiler cannot find the definition of the variable i
within this function, so it reports an error.
global
was proposed to solve this problem, explicitly telling the compiler that i
is a global variable, and then the compiler will look for the definition of i
outside the function. After executing i+=1
, i
remains a global variable, and its value is incremented by 1:
i = 0
def h():
global i
i += 1
h()
print(i)
23 Swap Two Elements
def swap(a, b):
return b, a
print(swap(1, 0)) # (0,1)
24 Operate on Function Objects
In [31]: def f():
...: print('i\'m f')
...:
In [32]: def g():
...: print('i\'m g')
...:
In [33]: [f,g][1]()
I'm g
Create a list of function objects, and call them based on the desired index for unified calling.
25 Generate Reverse Sequence
list(range(10,-1,-1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
The third parameter is negative, indicating that it starts decreasing from the first parameter, terminating at the second parameter (excluding this boundary)
26 Example of Five Types of Function Parameters
Python’s five types of parameters: positional parameters, keyword parameters, default parameters, variable positional or keyword parameters.
def f(a,*b,c=10,**d):
print(f'a:{a},b:{b},c:{c},d:{d}')
The default parameter c
cannot be located after the variable keyword parameter d
.
Call f
:
In [10]: f(1,2,5,width=10,height=20)
a:1,b:(2, 5),c:10,d:{'width': 10, 'height': 20}
The variable positional parameter b
is parsed as a tuple (2,5)
; c
takes the default value 10; d
is parsed as a dictionary.
Call f
again:
In [11]: f(a=1,c=12)
a:1,b:(),c:12,d:{}
a=1
is passed as a keyword parameter, while b
and d
are not passed values, and c
is passed as 12 instead of the default value.
Note that the parameter a
can be passed as f(1)
or f(a=1)
, which is more readable than the first method, and it is recommended to use f(a=1)
. If you want to enforce the use of f(a=1)
, you need to add an asterisk in front:
def f(*,a,**b):
print(f'a:{a},b:{b}')
At this point, calling f(1)
will throw an error: TypeError: f() takes 0 positional arguments but 1 was given
You can only call f(a=1)
successfully.
This indicates that the preceding *
takes effect, making it only possible to pass keyword parameters. How to check the type of this parameter? Use Python’s inspect
module:
In [22]: for name,val in signature(f).parameters.items():
...: print(name,val.kind)
...:
a KEYWORD_ONLY
b VAR_KEYWORD
You can see that the parameter a
is of type KEYWORD_ONLY
, which means it can only be a keyword parameter.
However, if f
is defined as:
def f(a,*b):
print(f'a:{a},b:{b}')
Check the parameter type:
In [24]: for name,val in signature(f).parameters.items():
...: print(name,val.kind)
...:
a POSITIONAL_OR_KEYWORD
b VAR_POSITIONAL
You can see that the parameter a
can be both a positional parameter and a keyword parameter.
27 Using Slice Objects
Generate a sequence about cake1:
In [1]: cake1 = list(range(5,0,-1))
In [2]: b = cake1[1:10:2]
In [3]: b
Out[3]: [4, 2]
In [4]: cake1
Out[4]: [5, 4, 3, 2, 1]
Generate another sequence:
In [5]: from random import randint
...: cake2 = [randint(1,100) for _ in range(100)]
...: # Similarly slice the first 10 elements with an interval of 2, getting slice d
...: d = cake2[1:10:2]
In [6]: d
Out[6]: [75, 33, 63, 93, 15]
As you can see, we used the same slicing method to slice two cakes, cake1 and cake2. Later, we found this slicing method is extremely classic
, and we used it to slice more container objects.
So, why not encapsulate this slicing method into an object? Thus, the slice
object was created.
Defining a slice object is very simple, like defining the above slicing method as a slice object:
perfect_cake_slice_way = slice(1,10,2)
# Slice cake1
cake1_slice = cake1[perfect_cake_slice_way]
cake2_slice = cake2[perfect_cake_slice_way]
In [11]: cake1_slice
Out[11]: [4, 2]
In [12]: cake2_slice
Out[12]: [75, 33, 63, 93, 15]
Results are consistent with the above.
For reverse sequence slicing, the slice
object also works:
a = [1,3,5,7,9,0,3,5,7]
a_ = a[5:1:-1]
named_slice = slice(5,1,-1)
a_slice = a[named_slice]
In [14]: a_
Out[14]: [0, 9, 7, 5]
In [15]: a_slice
Out[15]: [0, 9, 7, 5]
Frequent use of the same slice operation can use the slice object to extract it, reusing it while improving code readability.
28 Animation Demonstration of Lambda Functions
Some readers have reported that they do not know how to use lambda
functions and asked if I could explain it.
For example, the following lambda
function:
def max_len(*lists):
return max(*lists, key=lambda v: len(v))
There are two points of confusion:
-
What are the possible values of the parameter
v
? -
Does the
lambda
function have a return value? If so, what is the return value?
Call the above function to find the longest list among the following three:
r = max_len([1, 2, 3], [4, 5, 6, 7], [8])
print(f'The longer list is {r}')
The complete running process of the program is animated as follows:
Conclusion:
-
The possible value of parameter
v
is*lists
, which is an element of thetuple
. -
The return value of the
lambda
function is equal to the return value of the expression afterlambda v
colon.
4. Data Structures
29 Convert to Dictionary
Create a data dictionary
In [1]: dict()
Out[1]: {}
In [2]: dict(a='a',b='b')
Out[2]: {'a': 'a', 'b': 'b'}
In [3]: dict(zip(['a','b'],[1,2]))
Out[3]: {'a': 1, 'b': 2}
In [4]: dict([('a',1),('b',2)])
Out[4]: {'a': 1, 'b': 2}
30 Frozen Set
Create an immutable set.
In [1]: frozenset([1,1,3,2,3])
Out[1]: frozenset({1, 2, 3})
Since it is immutable, it does not have methods like add
and pop
like set
31 Convert to Set Type
Return a set
object, which does not allow duplicate elements:
In [159]: a = [1,4,2,3,1]
In [160]: set(a)
Out[160]: {1, 2, 3, 4}
32 Convert to Slice Object
class slice(start, stop[, step])
Returns a slice object representing the index set specified by range(start, stop, step)
, which improves code readability and maintainability.
In [1]: a = [1,4,2,3,1]
In [2]: my_slice_meaning = slice(0,5,2)
In [3]: a[my_slice_meaning]
Out[3]: [1, 2, 1]
33 Convert to Tuple
tuple()
converts an object to an immutable sequence type
In [16]: i_am_list = [1,3,5]
In [17]: i_am_tuple = tuple(i_am_list)
In [18]: i_am_tuple
Out[18]: (1, 3, 5)
5. Classes and Objects
34 Check if Callable
Check if an object is callable
In [1]: callable(str)
Out[1]: True
In [2]: callable(int)
Out[2]: True
In [18]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...:
In [19]: xiaoming = Student('001','xiaoming')
In [20]: callable(xiaoming)
Out[20]: False
If xiaoming()
can be called, you need to override the __call__
method of the Student
class:
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: def __call__(self):
...: print('I can be called')
...: print(f'my name is {self.name}')
...:
In [2]: t = Student('001','xiaoming')
In [3]: t()
I can be called
my name is xiaoming
35 ASCII Representation of Object
Call the object’s __repr__
method to obtain the return value of that method, as shown in the example, the return value is a string
>>> class Student():
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'id = '+self.id +', name = '+self.name
Call:
>>> xiaoming = Student(id='1',name='xiaoming')
>>> xiaoming
id = 1, name = xiaoming
>>> ascii(xiaoming)
'id = 1, name = xiaoming'
36 Class Method
classmethod
decorator corresponds to a function that does not need to be instantiated, does not require the self
parameter, but the first parameter needs to be cls
representing the class itself, which can be used to call class properties, class methods, instantiate objects, etc.
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: @classmethod
...: def f(cls):
...: print(cls)
37 Dynamically Delete Attributes
Delete an object’s attribute
In [1]: delattr(xiaoming,'id')
In [2]: hasattr(xiaoming,'id')
Out[2]: False
38 View All Methods of an Object
Without parameters, it returns a list of variables, methods, and defined types in the current scope
; with parameters, it returns the list of attributes and methods of the parameter
.
In [96]: dir(xiaoming)
Out[96]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'name']
39 Dynamically Get Object Attributes
Get the attributes of an object
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: getattr(xiaoming,'name') # Get the name attribute value of the instance xiaoming
Out[3]: 'xiaoming'
40 Check if Object Has This Attribute
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: hasattr(xiaoming,'name')
Out[3]: True
In [4]: hasattr(xiaoming,'address')
Out[4]: False
41 Object Memory Address
Return the memory address of the object
In [1]: id(xiaoming)
Out[1]: 98234208
42 isinstance
Determine if object is an instance of classinfo, returns true if so
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: isinstance(xiaoming,Student)
Out[3]: True
43 Parent-Child Relationship Identification
In [1]: class undergraduate(Student):
...: def studyClass(self):
...: pass
...: def attendActivity(self):
...: pass
In [2]: issubclass(undergraduate,Student)
Out[2]: True
In [3]: issubclass(object,Student)
Out[3]: False
In [4]: issubclass(Student,object)
Out[4]: True
If the class is a subclass of any element in the classinfo
tuple, it will also return True
In [1]: issubclass(int,(int,float))
Out[1]: True
44 Root of All Objects
object
is the base class of all classes
In [1]: o = object()
In [2]: type(o)
Out[2]: object
45 Two Ways to Create Properties
Return property attributes, typical usage:
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
# Create property attribute using property class
x = property(getx, setx, delx, "I'm the 'x' property.")
Using Python decorators to achieve the same effect as above:
class C:
def __init__(self):
self._x = None
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
46 Check Object Type
class type
(name, bases, dict)
When passing one parameter, it returns the type of object:
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...:
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: type(xiaoming)
Out[3]: __main__.Student
In [4]: type(tuple())
Out[4]: tuple
47 Metaclasses
xiaoming
, xiaohong
, xiaozhang
are all students, this group is called Student
.
A common way to define a class in Python is to use the keyword class
In [36]: class Student(object):
...: pass
xiaoming
, xiaohong
, xiaozhang
are instances of the class:
xiaoming = Student()
xiaohong = Student()
xiaozhang = Student()
After creation, the __class__
attribute of xiaoming
returns the Student
class
In [38]: xiaoming.__class__
Out[38]: __main__.Student
The question is, what does the Student
class have as a __class__
attribute? If it has, what is it?
In [39]: xiaoming.__class__.__class__
Out[39]: type
Wow, the program does not report an error, it returns type
So, we can guess: the Student
class is of type type
In other words, in Python, everything is an object, including classes.
The class that describes the Student
class is called a metaclass.
Following this logic, the class that describes the metaclass is also called a metaclass, just kidding~ The class that describes the metaclass is also called a metaclass.
Smart friends will ask, since the Student
class can create instances, can the type
class create instances? If it can, its instances are called: classes. You are very smart!
That’s right, the type
class can definitely create instances, such as the Student
class.
In [40]: Student = type('Student',(),{})
In [41]: Student
Out[41]: __main__.Student
It is exactly the same as the Student
class created using the class
keyword.
Because Python classes are also objects, they support operations similar to xiaoming
and xiaohong
objects. They support:
-
Assignment
-
Copying
-
Adding attributes
-
As function parameters
In [43]: StudentMirror = Student # Direct assignment of class # Direct assignment of class
In [44]: Student.class_property = 'class_property' # Add class property
In [46]: hasattr(Student, 'class_property')
Out[46]: True
Metaclasses are indeed not used that much, but perhaps understanding these can help in some situations. Even the leader of the Python community, Tim Peters
, said:
“Metaclasses are deep magic, and 99% of users should not worry about them at all.
6. Tools
48 Enumerate Object
Returns an object that can be enumerated, the object’s next()
method will return a tuple.
In [1]: s = ["a","b","c"]
...: for i ,v in enumerate(s,1):
...: print(i,v)
...:
1 a
2 b
3 c
49 Check Variable Size in Bytes
In [1]: import sys
In [2]: a = {'a':1,'b':2.0}
In [3]: sys.getsizeof(a) # Occupies 240 bytes
Out[3]: 240
50 Filter
Set filtering conditions in a function, iterate elements, and retain elements whose return value is True
:
In [1]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
In [2]: list(fil)
Out[2]: [11, 45, 13]
51 Return Object’s Hash Value
Return the hash value of the object. It is worth noting that custom instances are hashable, while list
, dict
, set
, and other mutable objects are unhashable.
In [1]: hash(xiaoming)
Out[1]: 6139638
In [2]: hash([1,2,3])
# TypeError: unhashable type: 'list'
52 One-Click Help
Return the help documentation of the object
In [1]: help(xiaoming)
Help on Student in module __main__ object:
class Student(builtins.object)
| Methods defined here:
|
| __init__(self, id, name)
|
| __repr__(self)
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
53 Get User Input
Get user input content
In [1]: input()
aa
Out[1]: 'aa'
54 Create Iterator Type
Use iter(obj, sentinel)
to return an iterable object, sentinel
can be omitted (once iterated to this element, terminate immediately)
In [1]: lst = [1,3,5]
In [2]: for i in iter(lst):
...: print(i)
...:
1
3
5
In [1]: class TestIter(object):
...: def __init__(self):
...: self.l=[1,3,2,3,4,5]
...: self.i=iter(self.l)
...: def __call__(self): # The instance of the class that defines the __call__ method is callable
...: item = next(self.i)
...: print ("__call__ is called,fowhich would return",item)
...: return item
...: def __iter__(self): # Support iteration protocol (i.e., define __iter__() function)
...: print ("__iter__ is called!!")
...: return iter(self.l)
In [2]: t = TestIter()
In [3]: t() # Because it implements __call__, the instance t can be called
__call__ is called,which would return 1
Out[3]: 1
In [4]: for e in TestIter(): # Because it implements __iter__ method, t can be iterated
...: print(e)
...:
__iter__ is called!!
1
3
2
3
4
5
55 Open File
Return a file object
In [1]: fo = open('D:/a.txt',mode='r', encoding='utf-8')
In [2]: fo.read()
Out[2]: '\ufefflife is not so long,\nI use Python to play.'
Mode value table:
Character | Meaning |
---|---|
'r' |
Read (default) |
'w' |
Write, truncating the file first |
'x' |
Exclusive creation, fails if the file already exists |
'a' |
Write, appending to the end if the file exists |
'b' |
Binary mode |
't' |
Text mode (default) |
'+' |
Open for updating (reading and writing) |
56 Create Range Sequence
-
range(stop)
-
range(start, stop[,step])
Generate an immutable sequence:
In [1]: range(11)
Out[1]: range(0, 11)
In [2]: range(0,11,1)
Out[2]: range(0, 11)
57 Reverse Iterator
In [1]: rev = reversed([1,4,2,3,1])
In [2]: for i in rev:
...: print(i)
...:
1
3
2
4
1
58 Aggregate Iterator
Create an iterator that aggregates elements from each iterable object:
In [1]: x = [3,2,1]
In [2]: y = [4,5,6]
In [3]: list(zip(y,x))
Out[3]: [(4, 3), (5, 2), (6, 1)]
In [4]: a = range(5)
In [5]: b = list('abcde')
In [6]: b
Out[6]: ['a', 'b', 'c', 'd', 'e']
In [7]: [str(y) + str(x) for x,y in zip(a,b)]
Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']
59 Chained Operations
from operator import (add, sub)
def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)(a, b)
add_or_sub(1, 2, '-') # -1
60 Object Serialization
Object serialization refers to the process of converting an object in memory into a storable or transmittable format. In many scenarios, directly transmitting a class object is inconvenient.
However, once the object is serialized, it becomes more convenient, as it is customary for interface calls or web requests to generally use JSON strings for transmission.
In practical use, class objects are generally serialized. First, create a Student
type and create two instances.
class Student():
def __init__(self,**args):
self.ids = args['ids']
self.name = args['name']
self.address = args['address']
xiaoming = Student(ids = 1,name = 'xiaoming',address = '北京')
xiaohong = Student(ids = 2,name = 'xiaohong',address = '南京')
Import the JSON module and call the dump method to serialize the list object [xiaoming,xiaohong]
into the file json.txt
.
import json
with open('json.txt', 'w') as f:
json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2, sort_keys=True)
The generated file content is as follows:
[
{
"address":"北京",
"ids":1,
"name":"xiaoming"
},
{
"address":"南京",
"ids":2,
"name":"xiaohong"
}
]
Source:https://github.com/jackzhenguo/python-small-examples

One-click three connections, let’s learn together⬇️