Jak uzyskać listę atrybutów klas w Pythonie?

Klasa to zdefiniowany przez użytkownika plan lub prototyp, na podstawie którego tworzone są obiekty. Klasy umożliwiają łączenie danych i funkcjonalności. Utworzenie nowej klasy powoduje utworzenie nowego typu obiektu, umożliwiając tworzenie nowych instancji tego typu. Do każdej instancji klasy można przypisać atrybuty służące do utrzymywania jej stanu. Instancje klasy mogą również posiadać metody (zdefiniowane przez klasę) służące do modyfikowania jej stanu.

Przykład:

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

Wyjście :

COE COE Shivam Sachin COE 

Notatka: Aby uzyskać więcej informacji, zobacz Klasy i obiekty Pythona .

Uzyskiwanie listy atrybutów klas

Ważne jest, aby znać atrybuty, z którymi pracujemy. W przypadku małych danych łatwo jest zapamiętać nazwy atrybutów, natomiast podczas pracy z ogromnymi danymi trudno jest zapamiętać wszystkie atrybuty. Na szczęście w Pythonie dostępne są pewne funkcje umożliwiające wykonanie tego zadania.

Korzystanie z wbudowanej funkcji dir().

Aby uzyskać listę wszystkich atrybutów, metod wraz z niektórymi odziedziczonymi magicznymi metodami klasy, używamy wbudowanej funkcji o nazwie Ty() .

Przykład:

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

Wyjście :

pierwsza druga trzecia 2 Przekazując obiekt klasy ['__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'] Przez przekazanie samej klasy ['__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__', 'jeden', 'pokaż' , 'trzy dwa']

Korzystanie z metody getmembers().

Innym sposobem znalezienia listy atrybutów jest użycie modułu sprawdzać . Moduł ten udostępnia metodę o nazwie pobierz członków() która zwraca listę atrybutów i metod klasy.

Przykład:

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

Wyjście :

first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second') 

Korzystanie z magicznej metody __dict__().

Aby znaleźć atrybuty, możemy również skorzystać z metody magicznej __dykt__ . Ta metoda zwraca tylko atrybuty instancji.

Przykład:

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

Wyjście:

first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2]) 

Korzystanie z funkcji vars().

Aby znaleźć atrybuty, możemy również użyć funkcji vars(). Metoda ta zwraca słownik atrybutów instancji danego obiektu.

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

Wyjście:

first second third 2 {'attr': 2}