logo

Ako získať zoznam atribútov triedy v Pythone?

Trieda je užívateľsky definovaný plán alebo prototyp, z ktorého sa vytvárajú objekty. Triedy poskytujú prostriedky na spájanie údajov a funkcií. Vytvorením novej triedy sa vytvorí nový typ objektu, ktorý umožní vytvárať nové inštancie tohto typu. Každá inštancia triedy môže mať pripojené atribúty na udržanie svojho stavu. Inštancie triedy môžu mať aj metódy (definované svojou triedou) na úpravu jej stavu.

Príklad:

gb vs mb

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

>

>

Výkon :

COE COE Shivam Sachin COE>

Poznámka: Ďalšie informácie nájdete v časti Triedy a objekty Pythonu .

Získanie zoznamu atribútov triedy

Je dôležité poznať atribúty, s ktorými pracujeme. Pre malé údaje je ľahké zapamätať si názvy atribútov, ale pri práci s veľkými údajmi je ťažké zapamätať si všetky atribúty. Našťastie máme pre túto úlohu v Pythone k dispozícii niektoré funkcie.

Použitie vstavanej funkcie dir().

Aby sme získali zoznam všetkých atribútov, metód spolu s niektorými zdedenými magickými metódami triedy, používame vstavaný tzv.ty().

Príklad:

Python3




polymorfizmus

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

>

>

Výkon :

prvá druhá tretina 2 Odovzdaním objektu triedy ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge___', '_,_getattribute_', '_,_getattribute_ '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '___reduce_at_at '__sizeof__ ', '__str__', '__subclasshook__', '__weakref__', 'attr', 'one', 'show', 'three', 'two'] Absolvovaním samotnej triedy ['__class__', '__delattr__', '__dict__' , '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', __init__', '__init__', '__init__', '__init__', '__init__ ' __Module__, '__ne__', '__new__', '__Reduce__', '__reduce_ex__', '__repr__', '__Setattr__', '__sizeof__', '__str__', '' __subclasshook__ ',' __weakref__ ',' ',', 'show', ',', 'show', ',', ',', ',' show '', ',', ',', 'show', ',', '', 'show' '' , 'tri', 'dva']

Použitie metódy getmembers().

Ďalším spôsobom, ako nájsť zoznam atribútov, je použitie modulukontrolovať. Tento modul poskytuje metódu tzvgetmembers()ktorý vráti zoznam atribútov triedy a metód.

zoradený zoznam polí v jazyku Java

Príklad:

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

>

>

Výkon :

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

Použitie magickej metódy __dict__()

Na nájdenie atribútov môžeme použiť aj magickú metódu__diktovať__. Táto metóda vracia iba atribúty inštancie.

Príklad:

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

np výplň

>

>

Výkon:

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

Pomocou funkcie vars().

Na nájdenie atribútov môžeme použiť aj funkciu vars(). Táto metóda vracia slovník inštančných atribútov daného objektu.

Python3




stránky ako coomeet

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

>

>

Výkon:

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