个性化阅读
专注于IT技术分析

如何在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通过传递类[‘__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’, ‘3’, ‘two’]通过传递类本身[‘__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’ , “三个”, “两个”]

方法2:查找属性列表的另一种方法是使用模块检查。该模块提供了一种称为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])

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0) 打赏
未经允许不得转载:srcmini » 如何在Python中获取类属性列表?
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏