Wie erhalte ich eine Liste von Klassenattributen in Python?
Eine Klasse ist ein benutzerdefinierter Entwurf oder Prototyp, aus dem Objekte erstellt werden. Klassen bieten eine Möglichkeit, Daten und Funktionalität zu bündeln. Durch das Erstellen einer neuen Klasse wird ein neuer Objekttyp erstellt, sodass neue Instanzen dieses Typs erstellt werden können. Jeder Klasseninstanz können Attribute zur Beibehaltung ihres Zustands zugeordnet werden. Klasseninstanzen können auch (durch ihre Klasse definierte) Methoden zum Ändern ihres Zustands haben.
Beispiel:
Python3
# 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)> |
Ausgabe :
COE COE Shivam Sachin COE
Notiz: Weitere Informationen finden Sie unter Python-Klassen und -Objekte .
Abrufen einer Liste von Klassenattributen
Es ist wichtig, die Attribute zu kennen, mit denen wir arbeiten. Bei kleinen Datenmengen ist es einfach, sich die Namen der Attribute zu merken, bei der Arbeit mit großen Datenmengen ist es jedoch schwierig, sich alle Attribute zu merken. Glücklicherweise stehen uns für diese Aufgabe einige Funktionen in Python zur Verfügung.
Verwendung der integrierten dir()-Funktion
Um die Liste aller Attribute, Methoden sowie einiger geerbter magischer Methoden einer Klasse zu erhalten, verwenden wir einen integrierten Aufruf Du() .
Beispiel:
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))> |
Ausgabe :
erstes zweites drittes 2 Durch Übergabe des Objekts der Klasse ['__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'] Durch Übergabe der Klasse selbst ['__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' , 'drei zwei']
Verwendung der getmembers()-Methode
Eine andere Möglichkeit, eine Liste von Attributen zu finden, ist die Verwendung des Moduls prüfen . Dieses Modul stellt eine Methode namens bereit getmembers() das eine Liste von Klassenattributen und -methoden zurückgibt.
Beispiel:
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)> |
Ausgabe :
first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second') Verwenden der magischen Methode __dict__()
Um Attribute zu finden, können wir auch die magische Methode verwenden __dict__ . Diese Methode gibt nur Instanzattribute zurück.
Beispiel:
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())> |
Ausgabe:
first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2]) Verwendung der Funktion vars()
Um Attribute zu finden, können wir auch die Funktion vars() verwenden. Diese Methode gibt das Wörterbuch der Instanzattribute des angegebenen Objekts zurück.
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))> |
Ausgabe:
first second third 2 {'attr': 2}