Home > Backend Development > Python Tutorial > How to get all properties of an object in Python

How to get all properties of an object in Python

anonymity
Release: 2019-05-25 14:32:02
Original
8704 people have browsed it

Using reflection in Python, we can get all the attributes of an object. This mechanism is called reflection (which in turn lets the object tell us what it is) and is used to obtain information about unknown objects at runtime.

How to get all properties of an object in Python

The following are several built-in methods that can be used to check or access the properties of an object. These methods can be used on any object, not just the Cat instance object in the example;

#coding:utf-8
from a import *
cat = Cat('kitty')
print cat.name
cat.sayHi()    #调用实例方法
print dir(cat)
if hasattr(cat, 'name'): #检查实例是否有这个属性
    setattr(cat, 'name', 'tiger') #same as: a.name = 'tiger'
    print getattr(cat, 'name') #same as: print a.name
getattr(cat, 'sayHi')()
Copy after login

dir([obj]):

Call this method Will return a list containing most of the attribute names of obj (there will be some special attributes that are not included). The default value of obj is the current module object.
hasattr(obj, attr):
This method is used to check whether obj has an attribute named attr and returns a Boolean value.
getattr(obj, attr):
Calling this method will return the value of the attribute named attr value in obj. For example, if attr is 'bar', obj.bar will be returned.
setattr(obj, attr, val):
Calling this method will assign the value of obj’s attribute named attr to val. For example, if attr is 'bar', it is equivalent to obj.bar = val.

The above is the detailed content of How to get all properties of an object in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template