如何在Python中获取类属性列表?
类是用户定义的蓝图或原型,从中创建对象。类提供了一种将数据和功能捆绑在一起的方法。创建一个新类会创建一种新类型的对象,允许创建该类型的新实例。每个类实例都可以附加属性以维护其状态。类实例也可以具有用于修改其状态的方法(由其类定义)。
例子:
# Python program to demonstrate
# classes
class Student:
# class variable
stream = "COE"
# Constructor
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
# Driver's code
a = Student("Shivam", 3425)
b = Student("Sachin", 3624)
print(a.stream)
print(b.stream)
print(a.name)
print(b.name)
# Class variables can be accessed
# using class name also
print(Student.stream)
输出 :
COE
COE
Shivam
Sachin
COE
注意:有关详细信息,请参阅Python类和对象。
获取类属性列表
了解我们正在使用的属性很重要。对于小数据,很容易记住属性的名称,但在处理大数据时,很难记住所有属性。幸运的是,我们有一些Python函数可用于此任务。
方法 1:为了获取一个类的所有属性、方法以及一些继承的魔法方法的列表,我们使用了一个名为dir()
的内置函数。
例子:
class Number :
# Class Attributes
one = 'first'
two = 'second'
three = 'third'
def __init__(self, attr):
self.attr = attr
def show(self):
print(self.one, self.two, self.three, self.attr)
n = Number(2)
n.show()
# Passing both the object
# and class as argument
# to the dir method
print('\nBy passing object of class')
print(dir(n))
print('\nBy passing class itself ')
print(dir(Number))
输出 :
first second third 2
By passing object of class
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘attr’, ‘one’, ‘show’, ‘three’, ‘two’]
By passing class itself
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘one’, ‘show’, ‘three’, ‘two’]
方法 2:另一种查找属性列表的方法是使用模块inspect
。这个模块提供了一个名为getmemebers()
的方法,它返回一个类属性和方法的列表。
示例 1:
import inspect
class Number :
# Class Attributes
one = 'first'
two = 'second'
three = 'third'
def __init__(self, attr):
self.attr = attr
def show(self):
print(self.one, self.two, self.three, self.attr)
# Driver's code
n = Number(2)
n.show()
# getmembers() returns all the
# members of an object
for i in inspect.getmembers(n):
# to remove private and protected
# functions
if not i[0].startswith('_'):
# To remove other methods that
# doesnot start with a underscore
if not inspect.ismethod(i[1]):
print(i)
输出 :
first second third 2
('attr', 2)
('one', 'first')
('three', 'third')
('two', 'second')
方法 3:要查找属性,我们还可以使用魔术方法__dict__
。此方法仅返回实例属性。
例子:
class Number :
# Class Attributes
one = 'first'
two = 'second'
three = 'third'
def __init__(self, attr):
self.attr = attr
def show(self):
print(self.one, self.two, self.three, self.attr)
# Driver's code
n = Number(2)
n.show()
# using __dict__ to access attributes
# of the object n along with their values
print(n.__dict__)
# to only access attributes
print(n.__dict__.keys())
# to only access values
print(n.__dict__.values())
输出:
first second third 2
{'attr': 2}
dict_keys(['attr'])
dict_values([2])