Python中的vars()函数

这是Python中的一个内置函数。vars()方法只接受一个参数,这也是可选的。它把一个对象作为一个参数,这个参数可以是 一个模块、一个类、一个实例或任何具有_____;属性的对象。 语法:

null
vars(object)

如果模块、类、实例或任何其他对象具有_dict___属性,则该方法返回该对象的_dict__属性。 如果对象与属性不匹配,则会引发TypeError异常 .模块和实例等对象具有可更新的_dict_______;属性,但其他对象可能对其_dict___;属性有书面限制。 当传递空参数时,vars()的作用类似于locals()方法 这意味着本地字典只对读取有用,因为本地字典的更新被忽略。

Python3

# Python program to illustrate
# working of vars() method in Python
class Geeks:
def __init__( self , name1 = "Arun", num2 = 46 , name3 = "Rishab"):
self .name1 = name1
self .num2 = num2
self .name3 = name3
GeeksforGeeks = Geeks()
print ( vars (GeeksforGeeks))


输出:

{'num2': 46, 'name1': 'Arun', 'name3': 'Rishab'}

Python3

# Python program to illustrating
# the use of vars() and locals
# when no argument is passed and
# how vars() act as locals().
class Geeks( object ):
def __init__( self ):
self .num1 = 20
self .num2 = "this is returned"
def __repr__( self ):
return "Geeks() is returned"
def loc( self ):
ans = 21
return locals ()
# Works same as locals()
def code( self ):
ans = 10
return vars ()
def prog( self ):
ans = "this is not printed"
return vars ( self )
if __name__ = = "__main__":
obj = Geeks()
print (obj.loc())
print (obj.code())
print (obj.prog())


输出:

{'ans': 21, 'self': Geeks() is returned}{'ans': 10, 'self': Geeks() is returned}{'num1': 20, 'num2': 'this is returned'}

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享