Summary of common functions in Python

Python common functions

python hasattr()function

hasattr() The function is used to determine whether a class instance object contains the property or method of the specified name. The syntax of this function is as follows:

hasattr(obj, name)

Among them, obj refers to the instance object of a certain class, and name represents the specified attribute name or method name. At the same time, the function will feed back the result of the judgment (True or False) as a return value.

For example:

class CLanguage:
    def __init__ (self):
        self.name = "百度一下"
        self.add = "wwww.baidu.com"
    def say(self):
        print("我正在学Python")

clangs = CLanguage()
print(hasattr(clangs,"name"))
print(hasattr(clangs,"add"))
print(hasattr(clangs,"say"))

The program output is as follows:

True
True
True

Obviously, both the attribute name and the method name are within hasattr()the matching scope of the function. Therefore, we can only use this function to determine whether the instance object contains the attribute or method of the name, but we cannot accurately determine whether the name represents the attribute or the method.

python getattr() function

getattr() The function gets the value of a specified property in an instance object of a class . That's right, hasattr()unlike functions, this function will only lookup from all the properties contained in the class object.

getattr() The syntax of the function is as follows:

getattr(obj, name[, default])

Among them, obj indicates the specified class instance object, name indicates the specified attribute name, default but is an optional parameter, which is used to set the default return value of the function, that is, when the function search fails, if no default parameter is specified, the program will directly report AttributeError an error , otherwise the function returns defaultthe specified value.

For example:

class CLanguage:
    def __init__ (self):
        self.name = "百度一下"
        self.add = "www.baidu.com"
    def say(self):
        print("我正在学Python")

clangs = CLanguage()
print(getattr(clangs,"name"))
print(getattr(clangs,"add"))
print(getattr(clangs,"say"))
print(getattr(clangs,"display",'nodisplay'))

The program execution result is:

百度一下
www.baidu.com
<bound method CLanguage.say of <__main__.CLanguage object at 0x000001BC2E5B6D90>>
nodisplay

It can be seen that for the existing attributes in the class, getattr() their values ​​will be returned, and if the name is a method name, the state information of the method will be returned; conversely, if the s name is not owned by the class object, or the default will be returned parameter, or the program reports AttributeErroran error.

python setattr()function

setattr() The function of the function is relatively complicated, and its most basic function is to modify the attribute value in the class instance object. Secondly, it can also dynamically add properties or methods to instance objects.

setattr() The syntax of the function is as follows:

setattr(obj, name, value)

First, the following example demonstrates how to modify the attribute value of a class instance object through this function:

class CLanguage:
    def __init__ (self):
        self.name = "百度一下"
        self.add = "www.baidu.com"
    def say(self):
        print("我正在学Python")
clangs = CLanguage()
print(clangs.name)
print(clangs.add)
setattr(clangs,"name","必应")
setattr(clangs,"add","www.bing.com")
print(clangs.name)
print(clangs.add)

The result of running the program is:

百度一下
www.baidu.com
必应
www.bing.com

Even using setattr() functions, you can modify a class attribute into a class method, and you can also modify a class method into a class attribute. For example:

def say(self):
    print("我正在学Python")

class CLanguage:
    def __init__ (self):
        self.name = "百度一下"
        self.add = "www.baidu.com"

clangs = CLanguage()
print(clangs.name)
print(clangs.add)
setattr(clangs,"name",say)
clangs.name(clangs)

The result of running the program is:

百度一下
www.baidu.com
我正在学Python

Obviously, by modifying namethe value of the attribute say(this is an externally defined function), the original name attribute becomes a name() method.

When using setattr()a function to modify the attribute or method of the execution name in the instance object, if the name lookup fails, the Python interpreter will not report an error, but will dynamically add an attribute or method with the specified name to the instance object. For example:

def say(self):
    print("我正在学Python")

class CLanguage:
    pass

clangs = CLanguage()
setattr(clangs,"name","百度一下")
setattr(clangs,"say",say)
print(clangs.name)
clangs.say(clangs)

The program execution result is:

百度一下
我正在学Python

It can be seen that although CLanguageis an empty class, setattr()we clangs dynamically add a nameproperty and a say() method to the object through the function.

Python os.pathmodule common function usage

method illustrate
os.path.abspath(path) Returns path the absolute path.
os.path.basename(path) Gets path the base name of the path, which is paththe string from the end to the position of the last slash.
os.path.commonprefix(list) Returns list(multiple paths), path the longest path shared by all.
os.path.dirname(path) Returns path the directory portion of the path.
os.path.exists(path) Determine pathwhether the corresponding file exists, if it exists, return True; otherwise, return False. The difference with lexists()is that exists()it will automatically judge the invalid file link (similar to the shortcut of the file in the Windows system), but lexists() it will not.
os.path.lexists(path) Determine whether the path exists, and if so, return it True; otherwise, return it False.
os.path.expanduser(path) Convert path"~" and "~user" contained in to a user directory.
os.path.expandvars(path) Replace path" name" and "name" and "name""{name}”。
os.path.getatime(path) Returns paththe last access time (floating point seconds) of the file pointed to by .
os.path.getmtime(path) Returns the last modification time of the file in seconds.
os.path.getctime(path) Returns the creation time of the file in seconds since January 1, 1970 (aka Unix time).
os.path.getsize(path) Returns the size of the file, or returns an error if the file does not exist.
os.path.isabs(path) Determine whether it is an absolute path.
os.path.isfile(path) Determine whether the path is a file.
os.path.isdir(path) Determine whether the path is a directory.
os.path.islink(path) Determine whether the path is a link file (similar to the shortcut in Windows system).
os.path.ismount(path) Determine whether the path is a mount point.
os.path.join(path1[, path2[, ...]]) Combine directory and file names into one path.
os.path.normcase(path) Convert paththe case and slashes of the .
os.path.normpath(path) Canonical path string form.
os.path.realpath(path) Returns path the real path.
os.path.relpath(path[, start]) startCompute relative paths from .
os.path.samefile(path1, path2) Determine whether the directories or files are the same.
os.path.sameopenfile(fp1, fp2) Determine whether fp1 and fp2point to the same file.
os.path.samestat(stat1, stat2) Determine whether stat1and stat2point to the same file.
os.path.split(path) Split the path into dirname and basenamereturn a tuple.
os.path.splitdrive(path) Generally used under windows, returns a tuple consisting of drive name and path.
os.path.splitext(path) Split a path, returning a tuple of pathname and file extension.
os.path.splitunc(path) Split the path into mount points and files.
os.path.walk(path, visit, arg) Traversing path, calling the function when entering each directory visit, visitthe function must have 3 parameters (arg, dirname, names), dirnameindicating the directory name of the current directory, namesrepresenting all the file names in the current directory, argswhich is walkthe third parameter of .
os.path.supports_unicode_filenames Sets whether arbitrary Unicodecharacter strings can be used as file names.

Detailed explanation of Python os.environmodule environment variables

os.environVarious information about the system can be obtained in python by

1 Introduction

By os.environobtaining environment variables, what are environment variables? Environment variables are the means of communication between programs and the operating system. os.environ.get() Some characters should not be written into the code in plain text, such as database passwords and personal account passwords. If they are written into the environment variables of your own machine, you can just take them out when the program is used. In this way, developers use their own set of passwords when testing on the local machine, and use the company's public account and password when deploying in the production environment, which can increase security. os.environ is a dictionary, a dictionary of environment variables. For example, "HOME" is a key in this dictionary, if there is this key, return the corresponding value, if not, return None

2. Detailed explanation of the key field

os.environ.keys() All keys in the main directory are as follows:

>>>import os
>>>os.environ.keys()

KeysView(environ({
    
    'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\Administrator\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-N5CU52O', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'CONDA_DEFAULT_ENV': 'base', 'CONDA_PREFIX': 'D:\\Anaconda', 'CONDA_PROMPT_MODIFIER': '(base) ', 'CONDA_SHLVL': '1', 'DATAGRIP': 'D:\\DataGrip 2022.3\\bin;', 'DATASPELL': 'D:\\DataSpell 2022.3\\bin;', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\Administrator', 'IDEA_INITIAL_DIRECTORY': 'D:\\PyCharm 2022.3\\bin', 'LANG': 'en_US.UTF-8', 'LANGUAGE': '', 'LC_ALL': 'en_US.UTF-8', 'LOCALAPPDATA': 'C:\\Users\\Administrator\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-N5CU52O', 'NUMBER_OF_PROCESSORS': '12', 'ONEDRIVE': 'C:\\Users\\Administrator\\OneDrive', 'OS': 'Windows_NT', 'PATH': 

3. os.environ.get() Usage

os.environ It is a dictionary, which is a dictionary of environment variables, and the value corresponding to the key can be obtained through the get method (note that os.environthe type of is not <class 'dict'>, not all dictionary functions can be used)

os.environ.get() It is a method for modules in python os to obtain environment variables. If there is such a key, the corresponding value is returned, and if not, None is returned.

For example:

import os
print(os.environ.get("HOME")) # 返回None

You can also set a default value, return the corresponding value when the key exists, and return the default value when it does not exist

print(os.environ.get("HOME", "default"))	#环境变量HOME不存在,返回	default

4. Usage of environment variables

Set system environment variables

os.environ['环境变量名称']='环境变量值' # 其中key和value均为string类型
os.putenv('环境变量名称', '环境变量值')
os.environ.setdefault('环境变量名称', '环境变量值')

Modify system environment variables

os.environ['环境变量名称']='新环境变量值'

Get system environment variables

os.environ['环境变量名称']
os.getenv('环境变量名称')
os.environ.get('环境变量名称', '默认值')	#默认值可给可不给,环境变量不存在返回默认值

删除系统环境变量

del os.environ['环境变量名称']
del(os.environ['环境变量名称'])

判断系统环境变量是否存在

'环境变量值' in os.environ   # 存在返回 True,不存在返回 False

Guess you like

Origin blog.csdn.net/qq_43300880/article/details/128394865