logo

Python でクラス属性のリストを取得するにはどうすればよいですか?

クラスは、オブジェクトの作成元となるユーザー定義のブループリントまたはプロトタイプです。クラスは、データと機能を一緒にバンドルする手段を提供します。新しいクラスを作成すると、新しいタイプのオブジェクトが作成され、そのタイプの新しいインスタンスを作成できるようになります。各クラス インスタンスには、その状態を維持するために属性を付けることができます。クラス インスタンスには、その状態を変更するためのメソッド (そのクラスによって定義される) を持つこともできます。

例:



Python3






csma と csma cd

# 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 の関数がいくつかあります。

組み込みの dir() 関数の使用

すべての属性、メソッド、およびクラスのいくつかの継承されたマジック メソッドのリストを取得するには、と呼ばれる組み込みメソッドを使用します。あなた()

例:

Python3




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>(>' By passing object of class'>)> print>(>dir>(n))> print>(>' By passing class itself '>)> print>(>dir>(Number))>

>

>

出力:

最初 2 番目 3 番目 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', 'three', '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' 、「3」、「2」]

getmembers() メソッドの使用

属性のリストを検索する別の方法は、モジュールを使用することです。検査する。このモジュールは、と呼ばれるメソッドを提供します。getメンバー()クラスの属性とメソッドのリストを返します。

例:

Python3




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')>

__dict__() マジック メソッドの使用

属性を見つけるには、マジックメソッドを使用することもできます__dict__。このメソッドはインスタンス属性のみを返します。

例:

Python3




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])>

vars() 関数の使用

属性を見つけるには、vars() 関数を使用することもできます。このメソッドは、指定されたオブジェクトのインスタンス属性の辞書を返します。

Python3




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()> # using the vars function> print>(>vars>(n))>

gimpのフォントのリスト
>

>

出力:

first second third 2 {'attr': 2}>