Operating environment for this tutorial :windows7 system ,Python3 edition ,Dell G3 computer .
Built in function classification :
*
Mathematical operation (7 individual )
*
Type conversion (24 individual )
*
Sequence operation (8 individual )
*
Object operation (7 individual )
*
Reflection operation (8 individual )
*
Variable operation (2 individual )
*
Interoperation (2 individual )
*
File operation (1 individual )
*
Compile execution (4 individual )
*
Decorator (3 individual )
Mathematical operation
abs: Find the absolute value of a value
1
2
>>> abs(-2)
2
pmod: Returns the quotient and remainder of two numeric values
1
2
3
4
>>> pmod(5,2)
(2, 1)
>> pmod(5.5,2)
(2.0, 1.5)
max: Returns the maximum value of an element in an iteratible object or the maximum value of all parameters
1
2
3
4
>>> max(1,2,3) # afferent 3 Parameters take 3 Whichever is greater
3
>>> max('1234') # afferent 1 Iteratible objects , Take its maximum element value
'4'
1
2
3
4
>>> max(-1,0) # The value defaults to the larger value
0
>>> max(-1,0,key = abs) # Absolute value function passed in , Then the absolute value of all parameters will be calculated and the larger one will be taken
-1
min: Returns the minimum value of an element in an iteratible object or the minimum value of all parameters
1
2
3
4
>>> min(1,2,3) # afferent 3 Parameters take 3 Whichever is smaller
1
>>> min('1234') # afferent 1 Iteratible objects , Take the minimum element value
'1'
1
2
3
4
>>> min(-1,-2) # The value defaults to the smaller value
-2
>>> min(-1,-2,key = abs) # Absolute value function passed in , Then the absolute value of all parameters will be calculated and the smaller one will be taken
-1
pow: Returns the power of two numeric values or their modulo values with a specified integer
1
2
3
4
5
>>> pow(2,3)
>>> 2**3
>>> pow(2,3,5)
>>> pow(2,3)%5
round: Rounding evaluation of floating point numbers
1
2
3
4
>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149
sum: Sum each element in an iteratable object whose element type is numeric
1
2
3
4
5
6
7
8
# Incoming iteratible object
>>> sum((1,2,3,4))
10
# Element type must be numeric
>>> sum((1.5,2.5,3.5,4.5))
12.0
>>> sum((1,2,3,4),-10)
0
Type conversion
bool: Create a new Boolean value based on the logical value of the passed in parameter
1
2
3
4
5
6
>>> bool() # No parameters passed in
False
>>> bool(0) # numerical value 0, The null sequence is equivalent to False
False
>>> bool(1)
True
int: Create a new integer based on the passed in parameter
1
2
3
4
5
6
>>> int() # When parameters are not passed in , Get results 0.
0
>>> int(3)
3
>>> int(3.6)
3
float: Create a new floating point number based on the passed in parameters
1
2
3
4
5
6
>>> float() # When parameters are not provided , return 0.0
0.0
>>> float(3)
3.0
>>> float('3')
3.0
complex: Create a new complex number based on the passed in parameter
1
2
3
4
5
6
>>> complex() # When neither parameter is provided , Return complex number 0j.
0j
>>> complex('1+2j') # Incoming string create complex
(1+2j)
>>> complex(1,2) # Create complex numbers by passing in values
(1+2j)
str: Returns the string representation of an object ( To users )
1
2
3
4
5
6
7
8
>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'
bytearray: Create a new byte array based on the passed in parameters
1
2
>>> bytearray(' chinese ','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
bytes: Create a new immutable byte array based on the passed in parameters
1
2
>>> bytes(' chinese ','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
memoryview: Create a new memory view object based on the passed in parameters
1
2
3
4
5
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
ord: return Unicode Integer corresponding to character
1
2
>>> ord('a')
97
chr: Returns the corresponding integer Unicode character
1
2
>>> chr(97) # Parameter type is integer
'a'
bin: Convert integer to 2 Hexadecimal Strings
1
2
>>> bin(3)
'0b11'
oct: Convert integer to 8 Hexadecimal digit string
1
2
>>> oct(10)
'0o12'
hex: Convert integer to 16 Hexadecimal Strings
1
2
>>> hex(15)
'0xf'
tuple: Create a new tuple based on the passed in parameters
1
2
3
4
>>> tuple() # Do not pass in parameters , Create empty tuple
()
>>> tuple('121') # Incoming iteratible object . Create a new tuple with its elements
('1', '2', '1')
list: Create a new list based on the passed in parameters
1
2
3
4
>>>list() # Do not pass in parameters , Create an empty list
[]
>>> list('abcd') # Incoming iteratible object , Create a new list with its elements
['a', 'b', 'c', 'd']
dict: Create a new dictionary based on the passed in parameters
1
2
3
4
5
6
7
8
>>> dict() # When no parameters are passed in , Return to empty dictionary .
{}
>>> dict(a = 1,b = 2) # A dictionary can be created by passing in key value pairs .
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # You can pass in mapping functions to create Dictionaries .
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # You can pass in an iteratable object to create a dictionary .
{'b': 2, 'a': 1}
set: Create a new collection based on the passed in parameters
1
2
3
4
5
>>>set() # Do not pass in parameters , Create an empty collection
set()
>>> a = set(range(10)) # Incoming iteratible object , Create collection
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
frozenset: Create a new immutable collection based on the passed in parameters
1
2
3
>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
enumerate: Create enumeration objects from iteratible objects
1
2
3
4
5
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # Specify starting value
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
range: Create a new one based on the passed in parameters range object
1
2
3
4
5
6
7
8
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # Output separately a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # Output separately a,b,c Element of
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])
>>>
iter: Create a new iteratible object based on the passed in parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> a = iter('abcd') # String sequence
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next(a)
StopIteration
slice: Create a new slice object based on the passed in parameters
1
2
3
4
5
6
7
8
9
>>> c1 = slice(5) # definition c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) # definition c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) # definition c3
>>> c3
slice(1, 10, 3)
super: Create a new proxy object with child and parent relationships based on the passed in parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Define parent class A
>>> class A(object):
def __init__(self):
print('A.__init__')
# Define subclasses B, inherit A
>>> class B(A):
def __init__(self):
print('B.__init__')
super().__init__()
#super Call parent method
>>> b = B()
B.__init__
A.__init__
object: Create a new object object
1
2
3
4
5
6
>>> a = object()
>>> a.name = 'kim' # Property cannot be set
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a.name = 'kim'
AttributeError: 'object' object has no attribute 'name'
Sequence operation
all: Determine whether each element of an iteratible object is True value
1
2
3
4
5
6
7
8
>>> all([1,2]) # The logical value of each element in the list is True, return True
True
>>> all([0,1,2]) # In the list 0 The logical value of is False, return False
False
>>> all(()) # Empty tuple
True
>>> all({}) # Empty dictionary
True
any: Determine whether the elements of an iteratable object have actions True Element of value >>> any([0,1,2]) # A list element has a True, Then return True
1
2
3
4
5
6
7
True
>>> any([0,0]) # List elements are all False, Then return False
False
>>> any([]) # Empty list
False
>>> any({}) # Empty dictionary
False
filter: Filter elements of iteratible objects using the specified method
1
2
3
4
5
6
7
8
>>> a = list(range(1,10)) # Define sequence
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): # Define odd judgment function
return x%2==1
>>> list(filter(if_odd,a)) # Filter odd numbers in sequence
[1, 3, 5, 7, 9]
map: Use the specified method to act on the elements of each passed in iteratible object , Generate a new iteratible object
1
2
3
4
5
>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]
next: Returns the next element value in an iteratible object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration
# afferent default After parameter , If the iteratable object still has elements that are not returned , Then its element values are returned in turn , If all elements have been returned , Then return default
Specified default value without throwing StopIteration abnormal
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
reversed: Invert the sequence to generate a new iteratible object
1
2
3
4
5
>>> a = reversed(range(10)) # afferent range object
>>> a # Type becomes iterator
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
sorted: Sort iteratible objects , Return to a new list
1
2
3
4
5
6
7
8
9
>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']
>>> sorted(a) # Default by character ascii Code sorting
['A', 'B', 'a', 'b', 'c', 'd']
>>> sorted(a,key = str.lower) # Convert to lowercase before sorting ,'a' and 'A' Same value ,'b' and 'B' Same value
['a', 'A', 'b', 'B', 'c', 'd']
zip: Aggregate elements at the same location in each passed in iterator , Returns a new tuple type iterator
1
2
3
4
>>> x = [1,2,3] # length 3
>>> y = [4,5,6,7,8] # length 5
>>> list(zip(x,y)) # Take the minimum length 3
[(1, 4), (2, 5), (3, 6)]
Object operation
help: Returns help information for an object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
***************************
dir: Returns the list of properties in the object or current scope
1
2
3
4
5
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2'
,'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',
'trunc']
id: Returns the unique identifier of the object
1
2
3
>>> a = 'some text'
>>> id(a)
69228568
hash: Get the hash value of the object
1
2
>>> hash('good good study')
1032709256
type: Returns the type of the object , Or create a new type based on the passed in parameters
1
2
3
4
5
6
7
8
>>> type(1) # Returns the type of the object
<class 'int'>
# use type Function creation type D, Contains attributes InfoD
>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))
>>> d = D()
>>> d.InfoD
'some thing defined in D'
len: Returns the length of the object
1
2
3
4
5
6
7
8
>>> len('abcd') # character string
>>> len(bytes('abcd','utf-8')) # Byte array
>>> len((1,2,3,4)) # tuple
>>> len([1,2,3,4]) # list
>>> len(range(1,5)) # range object
>>> len({'a':1,'b':2,'c':3,'d':4}) # Dictionaries
>>> len({'a','b','c','d'}) # aggregate
>>> len(frozenset('abcd')) # Immutable set
ascii: Returns the printable table string representation of an object
1
2
3
4
5
6
7
8
>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii(' chinese ') # wrong ascii character
"'\\u4e2d\\u6587'"
format: Format display values
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Parameters that strings can provide 's' None
>>> format('some string','s')
'some string'
>>> format('some string')
'some string'
# The parameters that integer values can provide are 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') # Convert to binary
'11'
>>> format(97,'c') # transformation unicode Into character
'a'
>>> format(11,'d') # convert to 10 Base
'11'
>>> format(11,'o') # convert to 8 Base
'13'
>>> format(11,'x') # convert to 16 Base Lowercase letters
'b'
>>> format(11,'X') # convert to 16 Base Capital letters
'B'
>>> format(11,'n') # and d equally
'11'
>>> format(11) # Default and d equally
'11'
# Floating point numbers can provide the following parameters 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') # Scientific counting , Default retention 6 Decimal places
'3.141593e+08'
>>> format(314159267,'0.2e') # Scientific counting , Specify retention 2 Decimal places
'3.14e+08'
>>> format(314159267,'0.2E') # Scientific counting , Specify retention 2 Decimal places , Capitalize E express
'3.14E+08'
>>> format(314159267,'f') # Decimal point counting , Default retention 6 Decimal places
'314159267.000000'
>>> format(3.14159267000,'f') # Decimal point counting , Default retention 6 Decimal places
'3.141593'
>>> format(3.14159267000,'0.8f') # Decimal point counting , Specify retention 8 Decimal places
'3.14159267'
>>> format(3.14159267000,'0.10f') # Decimal point counting , Specify retention 10 Decimal places
'3.1415926700'
>>> format(3.14e+1000000,'F') # Decimal point counting , Convert infinity to large and small letters
'INF'
#g The format of is special , hypothesis p Reserve the number of decimal places specified in the format , First try to format with scientific counting method , Get power exponent exp, If -4<=exp<p, Decimal counting method , And keep p-1-
exp Decimal places , Otherwise, count by decimal method , And press p-1 Keep decimal places
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p Not established , Count by scientific counting method , retain 0 Decimal place
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p Not established , Count by scientific counting method , retain 1 Decimal place
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p Not established , Count by scientific counting method , retain 2 Decimal place
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp
<p Not established , Count by scientific counting method , retain 0 Decimal place ,E Use uppercase
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p establish , Count by decimal method , retain 0 Decimal place
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p establish , Count by decimal method , retain 1 Decimal place
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p establish , Count by decimal method , retain 2 Decimal place
'3.14'
>>> format(0.00003141566,'.1n') # and g identical
'3e-05'
>>> format(0.00003141566,'.3n') # and g identical
'3.14e-05'
>>> format(0.00003141566) # and g identical
'3.141566e-05'
vars: Returns a dictionary of local variables and their values in the current scope , Or return the attribute list of the object
1
2
3
4
5
6
7
8
9
10
11
12
13
# Act on class instances
>>> class A(object):
pass
>>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = 'Kim'
>>> a.__dict__
{'name': 'Kim'}
>>> vars(a)
{'name': 'Kim'}
Reflection operation
__import__: Dynamic import module
1
2
index = __import__('index')
index.sayHello()
isinstance: Determine whether an object is an instance of any class element in a class or type tuple
1
2
3
4
5
6
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True
issubclass: Determine whether a class is a subclass of another class or any class element in a type tuple
1
2
3
4
5
6
7
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False
>>> issubclass(bool,(str,int))
True
hasattr: Check whether the object contains attributes
1
2
3
4
5
6
7
8
9
10
11
# Define class A
>>> class Student:
def __init__(self,name):
self.name = name
>>> s = Student('Aim')
>>> hasattr(s,'name') #a contain name attribute
True
>>> hasattr(s,'age') #a Does not contain age attribute
False
getattr: Get the property value of the object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Define class Student
>>> class Student:
def __init__(self,name):
self.name = name
>>> getattr(s,'name') # Presence attribute name
'Aim'
>>> getattr(s,'age',6) # No attribute exists age, But default values are provided , Return to default
>>> getattr(s,'age') # No attribute exists age, No default value provided , Call error
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
setattr: Set attribute values for objects
1
2
3
4
5
6
7
8
9
10
11
>>> class Student:
def __init__(self,name):
self.name = name
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
delattr: Deleting an object's properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Define class A
>>> class A:
def __init__(self,name):
self.name = name
def sayHello(self):
print('hello',self.name)
# Test properties and methods
>>> a.name
' Wheat '
>>> a.sayHello()
hello Wheat
# Delete attribute
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
a.name
AttributeError: 'A' object has no attribute 'name'
callable: Detect whether the object can be called
1
2
3
4
5
6
7
8
9
10
11
12
>>> class B: # Define class B
def __call__(self):
print('instances are callable now.')
>>> callable(B) # class B Is a callable object
True
>>> b = B() # Call class B
>>> callable(b) # example b Is a callable object
True
>>> b() # Call instance b success
instances are callable now.
Variable operation
globals: Returns a dictionary of global variables and their values in the current scope
1
2
3
4
5
>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins'
(built-in)>,'__name__': '__main__', '__doc__': None, '__loader__': <class
'_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() # One more a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins'
(built-in)>,'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <
class '_frozen_importlib.BuiltinImporter'>}
locals: Returns a dictionary of local variables and their values in the current scope
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> def f():
print('before define a ')
print(locals()) # No variables in scope
a = 1
print('after define a')
print(locals()) # There is one in the scope a variable , Value is 1
>>> f
<function f at 0x03D40588>
>>> f()
before define a
{}
after define a
{'a': 1}
Interoperation
print: Plot output to standard output objects
1
2
3
4
5
6
>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?
input: Read user input value
1
2
3
4
>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'
File operation
open: Open the file using the specified mode and encoding , Return file read / write object
1
2
3
4
5
# t Read and write for text ,b Binary read / write
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()
Compile execution
compile: Compile strings into code or AST object , Enable it to pass exec Statement to execute or eval Perform evaluation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> # Process statement usage exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9
>>> # Simple evaluation expression eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
eval: Perform dynamic expression evaluation
1
2
>>> eval('1+2+3+4')
10
exec: Execute dynamic statement block
1
2
3
>>> exec('a=1+2') # Execute statement
>>> a
3
repr: Returns the string representation of an object ( To the interpreter )
1
2
3
4
5
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"
Decorator
property: Decorator for marking attributes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
>>> class C:
def __init__(self):
self._name = ''
@property
def name(self):
"""i'm the 'name' property."""
return self._name
@name.setter
def name(self,value):
if value is None:
raise RuntimeError('name can not be None')
else:
self._name = value
>>> c = C()
>>> c.name # Access properties
''
>>> c.name = None # Validate when setting properties
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
c.name = None
File "<pyshell#81>", line 11, in name
raise RuntimeError('name can not be None')
RuntimeError: name can not be None
>>> c.name = 'Kim' # set a property
>>> c.name # Access properties
'Kim'
>>> del c.name # Delete attribute , Not available deleter Cannot be deleted
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'
classmethod: Decorator that identifies a method as a class method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> class C:
@classmethod
def f(cls,arg1):
print(cls)
print(arg1)
>>> C.f(' Class object calls class method ')
<class '__main__.C'>
Class object calls class method
>>> c = C()
>>> c.f(' Class instance object calls class method ')
<class '__main__.C'>
Class instance object calls class method
staticmethod: Decorator with static marking method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Using decorators to define static methods
>>> class Student(object):
def __init__(self,name):
self.name = name
@staticmethod
def sayHello(lang):
print(lang)
if lang == 'en':
print('Welcome!')
else:
print(' Hello !')
>>> Student.sayHello('en') # Class call ,'en' To lang parameter
en
Welcome!
>>> b = Student('Kim')
>>> b.sayHello('zh') # Class instance object call ,'zh' To lang parameter
zh
Hello
Technology
Daily Recommendation