The following editor will bring you a must-read operation for getting started with Python basics. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
Here are the methods and techniques commonly used in developing with python. If there are any mistakes, you are welcome to criticize and correct me.
Key points: Query the characteristics of classes and variables during development, the type is the class, the use of assertions, judgment of dark and shallow copy, etc.
Python script files are encoded using UTF-8, so when Chinese characters are found When garbled characters appear, you should consider whether the text file uses UTF-8 encoding.
If you want to specify different encodings, you need to add such a comment at the beginning of the source code file:
# -*- coding: utf-8 -*-
If python is running in linux and unix systems, You need to add in the first line of the source code:
#!/usr/bin/python3
How to get the contents of each module, variable, class, etc. in python?
Queries about help groups in Python can be obtained through variables __all__, __dict__, functions help(), and dir().
If __all__ is defined in a class or module, it generally contains features that can be called externally. If it is defined without assignment, it will automatically be filled with features that do not start with an underscore. If there is no parameter __all__python will prompt an AttributeError attribute error.
__dict__ generally gives the characteristics (including attributes and methods) defined in the class or module, which are output in the form of a dictionary using tuples to represent parameters and parameter values (parameters, parameter values or descriptions)
List's __dict__ view
>>> list.__dict__ 2 mappingproxy({'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, '__lt__': <slot wrapper '__lt__' of 'list' objects>, '__le__': <slot wrapper '__le__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>, '__ne__': <slot wrapper '__ne__' of 'list' objects>, '__gt__': <slot wrapper '__gt__' of 'list' objects>, '__ge__': <slot wrapper '__ge__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>, '__init__': <slot wrapper '__init__' of 'list' objects>, '__len__': <slot wrapper '__len__' of 'list' objects>, '__getitem__': <method '__getitem__' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>, '__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>, '__mul__': <slot wrapper '__mul__' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>, '__contains__': <slot wrapper '__contains__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>, '__new__': <built-in method __new__ of type object at 0x000000005BBAF530>, '__reversed__': <method '__reversed__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>, 'clear': <method 'clear' of 'list' objects>, 'copy': <method 'copy' of 'list' objects>, 'append': <method 'append' of 'list' objects>, 'insert': <method 'insert' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>, 'remove': <method 'remove' of 'list' objects>, 'index': <method 'index' of 'list' objects>, 'count': <method 'count' of 'list' objects>, 'reverse': <method 'reverse' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"})
dir() will give all the available feature attributes in the form of a list, without values and Attribute description:
list uses dir() to view
1 >>> dir(list) 2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Generally speaking, just use __dict__ and dir(). Of course, many times You need help() to view detailed documents (actually the content in __doc__):
list Use help() to view
help(list) Help on class list in module builtins: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | -- More --
If we now An object a = list() is created. Now if you want to get the characteristic methods of object a, you can also use dir() and help().
What needs to be emphasized here is that the power of dir() and help() can not only check the class, but also the variables we define. This way we can get more content during the encoding process.
Search for variable a containing methods in a=1
>>> a=1 >>> dir(a) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__pmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floorp__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> help(a) Help on int object: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | -- More --
Search for variables and object types and other operations
In addition to using dir(), help(), __all__, __dict__ to view the content of the original definition design in python, you can use many defined features to obtain more information:
Methods to get variable types and object types:
Query variables and class types through __class__
>>> a =1 >>> a.__class__ <class 'int'> >>> b = 1.0 >>> b.__class__ <class 'float'> >>> c = '' >>> c.__class__ <class 'str'> >>> d = list() >>> d.__class__ <class 'list'> >>> e = tuple() >>> e.__class__ <class 'tuple'> >>> f = dict() >>> f.__class__ <class 'dict'> >>> list.__class__ <class 'type'> >>> dict.__class__ <class 'type'> >>> tuple.__class__ <class 'type'> >>> object.__class__ <class 'type'> >>> None.__class__ <class 'NoneType'>
Through the above code we find that if class For type, in fact, this itself is the definition of a class, if it is something else, it is an object.
Have you ever thought that basic variables in python are also objects?
In general languages, our types are divided into integers, floating point types, strings, etc. But in Python these types are actually defined in the form of classes, and classes also inherit top-level superclasses.
Use __class__ to view the type and __bases__ to view the super class
>>> a = 1 >>> a.__class__ <class 'int'> >>> int.__class__ <class 'type'> >>> str.__class__ <class 'type'> >>> bool.__class__ <class 'type'> >>> list.__class__ <class 'type'> >>> dict.__class__ <class 'type'> >>> tuple.__class__ <class 'type'> >>> type.__class__ <class 'type'> >>> object.__class__ <class 'type'> >>> type.__bases__ (<class 'object'>,) >>> int.__bases__ (<class 'object'>,) >>> str.__bases__ (<class 'object'>,) >>> bool.__bases__ (<class 'int'>,) >>> float.__bases__ (<class 'object'>,) >>> object.__bases__ () >>>
I found out that no, the types we use are actually classes, except bool which inherits Class int, others inherit the super class object. The object class has no superclass. It should be said that type is a type class! Of course, the None type is NoneType, but NoneType is not a class. This means that None is a null value.
The content contained in the type class and the content contained in the object class
>>> dir(type) ['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro'] >>> dir(object) ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
is and id() allow us to see Clear the hidden relationships between variables!
We all know that python has the convenience of weak types in use. Of course, in python, there is only one variable with the same value! Why is this? This is because they all point to the same memory address. You can think of these variables as storing memory addresses one by one. Our assignment to them is just changing the memory addresses they point to! !
It is helpful to understand python from the perspective of pointers. The variable itself stores pointers. If you can understand this, then you can easily understand and use Python's variables and memory recycling mechanism.
A is B The function of the operation is to determine whether A is B. If it is true, it means that A and B are the same object. If it is false, it means that A and B are not the same object.
id(A) The function of the operation is to determine the id sequence number of A in the memory.
Let’s explain in detail the related phenomena in python:
1. Although A and B in python are the same Object, but after assigning a value to A, A and B are the same object again, because the assignment in python changes the address pointed by A to the address of another object, which is different from the address in B. The value of the object caused by the B address will not be affected by the A assignment.
2.python中同一个对象所具有的id可能是不同的,因为在没有指向该地址的变量时,python内存自动清理会清理掉这个对象。再次使用到具有相同数值的对象可能是在前一个对象自动清理之后创建的新对象。
针对第一个情况我们首先通过对True和False和数字来确定哪些值对象的id是系统自带的,即便这些值对象不被变量使用python内存清理也不会清理这些对象!
通过id来判断数值和布尔值中的值对象是否是系统自带的对象
>>> id(True) 1538937056 >>> id(False) 1538937088 >>> id(False) - id(True) 32 >>> id(-5) 1539416992 >>> id(-6) 1667933956912 >>> id(-4) 1539417024 >>> id(-4)-id(-5) 32 >>> id(-3)-id(-4) 32 >>> id(-3) 1539417056 >>> id(-2) 1539417088 >>> id(-2) - id(-3) 32 >>> id(255) 1539425312 >>> id(256) 1539425344 >>> id(256) - id(255) 32 >>> id(257) 1667904611440 >>> id(1.0) 1667904643192
你会发现数字-5到256是连续的,他们相邻的id值相差是32,意思是他们是32表示的数值。id返回的值就是他们在python中逻辑内存地址的值,在不同python进程中这些相同值对象返回的id值是一致的。而小于-5或者大于256的数值,小数,超过单个字符的字符串都是python在用户使用时创建的值对象,在不同的python进程中相同的值的id是不同的!其他值在不使用时有的就会被python内存清理程序清理掉释放内存!
当然,python中还有很多对象、类、函数等是python自创建的不会因为不使用而被内存清理程序清理掉。比如 int,None,dict,list。
不够值得一提的是 None is None是返回True 。并且id(None)的返回值是1538983120。这说明与其他脚本(比如javascript)不一样,None是空值,是一个唯一的空值对象,程序中所有的None都是相等的。都是同一个内存地址中存放的值。
很多情况下,我们想判断两个变量是否指向同一个内存地址块存放的值,可以使用is来判断。
python中对于全局变量,局部变量,外部变量有着额外的处理方式
如果一个函数中定义了与外部名称相同的变量,在函数内部如何能够获得外部定义的变量呢?在其他语言中,我们都知道局部变量会覆盖掉同名的外部变量。而在python中虽然也是这个逻辑,但是他提供了 3个函数来使得我们能够获得不同作用域中定义的同名的变量值。
globals()获取所有全局变量值
locals()获取所有局部变量值
nonlocals()获取所有外部变量值(因为python是支持函数嵌套的,内部函数如果想要获得外部函数局部变量的值可以使用这个)
在局部变量中获取全局变量中同名变量
>>> a = 234 >>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 234} >>> def s(): ... a = 'hello' ... print(locals()) ... >>> s() {'a': 'hello'} >>> def u(): ... a = 'world' ... c = globals()['a'] ... print(c) ... >>> u() 234
如上面代码显示的,在函数u()中a的值是‘world'而在全局变量中a的值是234,函数s()中局部变量a的值是'hello'通过globals()[变量名]就可以获得全局变量中同名的变量的值。
局部改变上段代码中同名的全局变量值
>>> def e(): ... a = 'sdf' ... globals()['a'] = a ... >>> e() >>> a 'sdf' >>>
The above is the detailed content of Summary of basic entry-level operations of Python. For more information, please follow other related articles on the PHP Chinese website!