Python标准内置函数(26-30)

版权声明:CSDN原创,请尊重三叔的版权,进Python学习乐园 群: 668758148,大家一起学习! https://blog.csdn.net/asd343442/article/details/84190152

1.26  函数globals()

在Python程序中,函数globals()的功能是以字典类型返回当前位置的全部全局变量,也就是返回表示当前全局符号表的字典。函数globals()总是当前模块的字典,在函数或者方法中,它是指定义的模块而不是调用的模块。

例如在下面的实例文件glo.py中,演示了使用函数globals()返回全部全局变量的过程。

print(globals())#没有设置变量

a = 1

print(globals())#多了一个a

a='toppr'#多了一个toppr

print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。

执行后会输出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None}

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None, 'a': 1}

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None, 'a': 'toppr'}

在上述执行效果中,第一行是变量为空时的执行效果,在最后显示为“None”。第二行是变量“a=1” 时的执行效果,在最后显示为“'a': 1”。第三行是变量“a='toppr'” 时的执行效果,在最后显示为“'a': 'toppr'”。

1.27  函数hasattr()

在Python程序中,函数hasattr()的功能是判断在指定对象中是否包含对应的属性。使用函数hasattr(object, name)的语法格式如下所示。

hasattr(object, name)
  1. object:对象。
  2. name:字符串,表示属性名。

如果字符串name是对象的一个属性则返回True,否则返回False。函数hasattr()实际上是调用getattr(object,name)函数,通过是否抛出AttributeError来判断是否含有属性。例如在下面的实例文件has.py中,演示了使用函数hasattr()判断在指定对象中是否包含对应的属性的过程。

# 定义类A

class Student:

    def __init__(self, name):

        self.name = name



s = Student('Aim')

print(hasattr(s, 'name'))           # a含有name属性

print(hasattr(s, 'age'))            # a不含有age属性



# 定义类Coordinate

class Coordinate:

    x = 10

    y = -5

    z = 0



point1 = Coordinate()

print(hasattr(point1, 'x'))  # 有该属性

print(hasattr(point1, 'y'))  # 有该属性

print(hasattr(point1, 'z'))  # 有该属性

print(hasattr(point1, 'no')) # 没有该属性

执行后会输出:

True

False

True

True

True

False

1.28  函数hash()

在Python程序中,函数hash()的功能是获取取一个对象(字符串或者数值等)的哈希值。使用函数hash()的语法格式如下所示。

hash(object)

参数object是一个对象,返回的哈希值是一个整数。哈希值用于在查找字典时快速地比较字典的键,相等数值的哈希值相同(即使它们的类型不同,比如1和1.0)。例如在下面的实例文件hash.py中,演示了使用函数hash()获取取一个对象的哈希值的过程。

print(hash('test'))            # 字符串

print(hash(1))                 # 数字

print(hash(str([1,2,3])))      # 集合

print(hash(str(sorted({'1':1}))))# 字典

#相等的数值,即使类型不一致,计算的哈希值是一样的。

print(1.0 == 1)

print(hash(1.0))

print(hash(1))

print(hash(1.0000))

执行后会输出:

749979671510942164

1

1217072518131548941

-8397379028218661641

True

1

1

1

1.29  函数help()

在Python程序中,使用函数help()的语法格式如下所示。

help([object])

函数help()的功能是调用内置的帮助系统,查看object函数或模块用途的详细说明。如果没有参数object,在解释器的控制台启动交互式帮助系统。如果参数object是一个字符串,该字符串被当作模块名、函数名、类名、方法名、关键字或者文档主题而被查询,在控制台上打印帮助页面。如果参数object是其它类型的某种对象,则会生成关于对象的帮助页面。例如下面演示了在解释器交互界面使用无参函数help()的过程。

>>> help() #不带参数



Welcome to Python 3.5's help utility!



If this is your first time using Python, you should definitely check out

the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.



Enter the name of any module, keyword, or topic to get help on writing

Python programs and using Python modules.  To quit this help utility and

return to the interpreter, just type "quit".



To get a list of available modules, keywords, symbols, or topics, type

"modules", "keywords", "symbols", or "topics".  Each module also comes

with a one-line summary of what it does; to list the modules whose name

or summary contain a given string such as "spam", type "modules spam".



#进入内置帮助系统  >>> 变成了 help>

help> str #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.

 ................................





help> 1 #不存在的模块名、类名、函数名

No Python documentation found for '1'.

Use help() to get the interactive help utility.

Use help(str) for help on the str class.



help> quit #退出内置帮助系统



You are now leaving help and returning to the Python interpreter.

If you want to ask for help on a particular object directly from the

interpreter, you can type "help(object)".  Executing "help('string')"

has the same effect as typing a particular string at the help> prompt.



# 已退出内置帮助系统,返回交互界面 help> 变成 >>>

>>>

当在解释器交互界面传入参数调用函数时,将查找参数是否是模块名、类名、函数名,如果则将显示其使用说明。例如下面演示了在解释器交互界面使用有参函数help()的过程。

>>> 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.

 | 

  ***************************

例如在下面的实例文件help.py中,演示了使用函数help()获取帮助信息的过程。

print(help('sys'))# 查看 sys 模块的帮助

print(help('str'))# 查看 str 数据类型的帮助



a = [1, 2, 3]

print(help(a))# 查看列表 list 帮助信息

print(help(a.append))# 显示list的append方法的帮助

执行后的效果如图1-1所示。

图1-1  执行效果

1.30  函数hex()

在Python程序中,使用函数hex()的语法格式如下所示。

hex(x)

函数hex()的功能是将10进制整数转换成16进制,以字符串形式表示。参数x是一个10进制整数。如果参数x不是Python int对象,则必须定义一个__index__()方法,返回一个整数。读者需要注意的是,如果要获取浮点型的十六进制字符串表示形式,需要使用float.hex()方法实现。例如在下面的实例文件hex.py中,演示了用函数hex()将10进制整数转换成16进制整数的过程。

#将10进制整数转换成16进制整数。

print(hex(15))

print(hex(16))

# 未定义__index__函数

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age



s = Student('Kim',10)

①print(hex(s))

在上述代码中,①处的s不是一个人整数,所以执行后会输出错误信息:

0xf

Traceback (most recent call last):

0x10

  File "hex.py", line 12, in <module>

    print(hex(s))

TypeError: 'Student' object cannot be interpreted as an integer

例如在下面的实例文件hex1.py中,演示了用函数hex()转换非整数的过程。

#定义__index__函数,并返回整数

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age

    def __index__(self):

        return self.age



s = Student('Kim',10)

print(hex(s))



#定义__index__函数,但是返回字符串

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age

    def __index__(self):

        return self.name #返回的是name,不是整数



s = Student('Kim',10)

print(hex(s))

执行后会输出:

0xa

Traceback (most recent call last):

  File "hex1.py", line 21, in <module>

    print(hex(s))

TypeError: __index__ returned non-int (type str)

猜你喜欢

转载自blog.csdn.net/asd343442/article/details/84190152
今日推荐