logo

Jak získat seznam atributů třídy v Pythonu?

Třída je uživatelsky definovaný plán nebo prototyp, ze kterého jsou vytvářeny objekty. Třídy poskytují prostředky pro sdružování dat a funkcí dohromady. Vytvořením nové třídy se vytvoří nový typ objektu, který umožňuje vytvářet nové instance tohoto typu. Ke každé instanci třídy mohou být připojeny atributy pro udržení jejího stavu. Instance třídy mohou mít také metody (definované její třídou) pro úpravu jejího stavu.

alternativy watchcartoononline.io

Příklad:



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ýstup :

COE COE Shivam Sachin COE>

Poznámka: Další informace viz Třídy a objekty Pythonu .

Získání seznamu atributů třídy

Je důležité znát atributy, se kterými pracujeme. U malých dat je snadné zapamatovat si názvy atributů, ale při práci s velkými daty je obtížné zapamatovat si všechny atributy. Naštěstí pro tento úkol máme v Pythonu k dispozici některé funkce.

Použití vestavěné funkce dir().

Abychom získali seznam všech atributů, metod spolu s některými zděděnými magickými metodami třídy, používáme vestavěný tzv.vy().

Pří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)> > 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ýstup :

první druhá třetina 2 Předáním objektu třídy ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge_gt_', '_,_getattribute_', '__getattribute_ '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '___reduce_at_, '_,''_at '__sizeof__ ', '__str__', '__subclasshook__', '__weakref__', 'attr', 'jeden', 'show', 'tři', 'dva'] Předáním samotné třídy ['__class__', '__delattr__', '__dict__' , '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', __hash,__', __init__', '__init__', '__init__', '__init__ ' __Module__ ',' __ne__ ',' __new__ ',' __reduce__ ',' __reduce_ex__ ',' __repr__ ',' __seTattr__ ',' __Sizeof__ ',' __ST__ ',' __SUBClasshook__ ',' __WEAKREFF , 'tři', 'dva']

Použití metody getmembers().

Dalším způsobem, jak najít seznam atributů, je použití modulukontrolovat. Tento modul poskytuje metodu tzvgetmembers()který vrací seznam atributů třídy a metod.

Pří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ýstup :

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

Použití magické metody __dict__()

K nalezení atributů můžeme také použít magickou metodu__diktovat__. Tato metoda vrací pouze atributy instance.

Pří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())>

>

>

Výstup:

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

Použití funkce vars().

K nalezení atributů můžeme také použít funkci vars(). Tato metoda vrací slovník instančních atributů daného objektu.

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

>

>

Výstup:

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