|
Python中查看对象的所有属性和方法以及查看属性是否存在作者:爱编程的小金毛球球日期:2023年12月3日Python提供许多的内置函数和模块来帮助开发人员查看对象的所有属性,例如:dir(),vars(),__dict__等。dir()函数查看对象的所有属性dir()是Python内置函数之一,帮助检查给定对象的所有方法和属性,包含方法、变量、函数等。dir()函数用于枚举一个类或实例中的所有属性和方法。语法:dir([object=None])1#!/usr/bin/envpython3#定义一个字符串变量,并查看其所有属性和方法sweet_talk='iloveu'print(dir(sweet_talk))#输出(list):['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs','find','format','format_map','index','isalnum','isalpha','isascii','isdecimal','isdigit','isidentifier','islower','isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower','lstrip','maketrans','partition','removeprefix','removesuffix','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper','zfill']123456789101112131415使用vars()函数和__dict__属性来查看对象的所有属性与dir()函数不同,vars()函数和__dict__属性是专门用来查看对象的属性和值,我们可以使用vars()函数来查看用户自定义对象或内置对象的属性,使用__dict__属性来查看给定对象的所有属性。vars()函数和__dict__属性使用方法类似。语法:vars([object=None])1#定义一个Student类,属性包括name、sex、ageclassStudent: def__init__(self,name,sex,age): self.name=name self.sex=sex self.age=ageJack=Student("Jack","man",10)Tom=Student("Tom","woman",9)print(vars(Jack))print(Tom.__dict__)#输出(dict):{'name':'Jack','sex':'man','age':10}{'name':'Tom','sex':'woman','age':9}123456789101112131415使用hasattr()函数判断对象是否包含对应属性语法:hasattr(object,name)object--对象name--字符串,属性名存在该属性返回True,否则返回False1234以上面定义的Student类为例print(hasattr(Tom,'name'))print(hasattr(Jack,'score'))#输出TrueFalse123456
|
|