Come ottenere un elenco di attributi di classe in Python?
Una classe è un progetto o un prototipo definito dall'utente da cui vengono creati gli oggetti. Le classi forniscono un mezzo per raggruppare insieme dati e funzionalità. La creazione di una nuova classe crea un nuovo tipo di oggetto, consentendo la creazione di nuove istanze di quel tipo. A ogni istanza di classe possono essere associati attributi per mantenerne lo stato. Le istanze della classe possono anche avere metodi (definiti dalla sua classe) per modificarne lo stato.
Esempio:
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)> |
Produzione :
COE COE Shivam Sachin COE
Nota: Per ulteriori informazioni, fare riferimento a Classi e oggetti Python .
Ottenere un elenco di attributi di classe
È importante conoscere gli attributi con cui stiamo lavorando. Per dati di piccole dimensioni è facile ricordare i nomi degli attributi, ma quando si lavora con dati di grandi dimensioni è difficile memorizzare tutti gli attributi. Fortunatamente, abbiamo alcune funzioni in Python disponibili per questo compito.
Utilizzando la funzione dir() incorporata
Per ottenere l'elenco di tutti gli attributi, metodi insieme ad alcuni metodi magici ereditati di una classe, utilizziamo un built-in chiamato Voi() .
Esempio:
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))> |
Produzione :
primo secondo terzo 2 Passando l'oggetto della classe ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__dimensione__ ', '__str__', '__subclasshook__', '__weakref__', 'attr', 'one', 'show', 'tre', 'due'] Passando la classe stessa ['__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' , 'tre', 'due']
Utilizzo del metodo getmembers()
Un altro modo per trovare un elenco di attributi è utilizzare il modulo ispezionare . Questo modulo fornisce un metodo chiamato ottienimembri() che restituisce un elenco di attributi e metodi di classe.
Esempio:
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)> |
Produzione :
first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second') Utilizzando il metodo magico __dict__()
Per trovare gli attributi possiamo anche usare il metodo magico __detto__ . Questo metodo restituisce solo gli attributi dell'istanza.
Esempio:
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())> |
Produzione:
first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2]) Utilizzando la funzione vars()
Per trovare gli attributi possiamo anche usare la funzione vars(). Questo metodo restituisce il dizionario degli attributi di istanza dell'oggetto specificato.
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))> |
Produzione:
first second third 2 {'attr': 2}