首页 > Python资料 博客日记

Python中查看对象的所有属性和方法以及查看属性是否存在

2024-03-23 03:00:05Python资料围观31

本篇文章分享Python中查看对象的所有属性和方法以及查看属性是否存在,对你有帮助的话记得收藏一下,看Python资料网收获更多编程知识

Python中查看对象的所有属性和方法以及查看属性是否存在

作者:爱编程的小金毛球球 日期:2023年12月3日

Python提供许多的内置函数和模块来帮助开发人员查看对象的所有属性,例如:dir(),vars(),__dict__等。

dir()函数查看对象的所有属性

dir()是Python内置函数之一,帮助检查给定对象的所有方法和属性,包含方法、变量、函数等。dir()函数用于枚举一个类或实例中的所有属性和方法。

语法:dir([object=None])
#!/usr/bin/env python3
# 定义一个字符串变量,并查看其所有属性和方法

sweet_talk= 'i love u'
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']

使用vars()函数和__dict__属性来查看对象的所有属性

与dir()函数不同,vars()函数和__dict__属性是专门用来查看对象的属性和值,我们可以使用vars()函数来查看用户自定义对象或内置对象的属性,使用__dict__属性来查看给定对象的所有属性。vars()函数和__dict__属性使用方法类似。

语法:vars([object=None])
# 定义一个Student类,属性包括name、sex、age
class Student:
	def __init__(self, name, sex, age):
		self.name = name
		self.sex = sex
		self.age = age

Jack = 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}

使用hasattr()函数判断对象是否包含对应属性

语法:hasattr(object, name)
object--对象
name--字符串,属性名
存在该属性返回True,否则返回False

以上面定义的Student类为例

print(hasattr(Tom, 'name'))
print(hasattr(Jack, 'score'))

#输出
True
False

版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐