Kaip gauti klasės atributų sąrašą Python?
Klasė yra vartotojo apibrėžtas projektas arba prototipas, iš kurio kuriami objektai. Klasės suteikia galimybę sujungti duomenis ir funkcijas. Sukūrus naują klasę sukuriamas naujo tipo objektas, leidžiantis sukurti naujus tokio tipo egzempliorius. Kiekvienas klasės egzempliorius gali turėti prie jo pridėtus atributus, kad išlaikytų savo būseną. Klasės egzemplioriai taip pat gali turėti metodus (apibrėžtus pagal klasę), skirtus jos būsenai keisti.
Pavyzdys:
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)> |
Išvestis:
COE COE Shivam Sachin COE
Pastaba: Norėdami gauti daugiau informacijos, žr Python klasės ir objektai .
Klasės atributų sąrašo gavimas
Svarbu žinoti atributus, su kuriais dirbame. Mažiems duomenims lengva įsiminti atributų pavadinimus, tačiau dirbant su dideliais duomenimis, sunku įsiminti visus atributus. Laimei, šiai užduočiai atlikti turime keletą Python funkcijų.
Naudojant integruotą dir() funkciją
Norėdami gauti visų klasės atributų, metodų sąrašą ir kai kuriuos paveldėtus magiškus metodus, naudojame integruotą vadinamą tu() .
Pavyzdys:
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))> |
Išvestis:
pirmas antras trečdalis 2 Perduodant objektą iš klasės ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__'t, _ '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', ____'reduce ', '__dydis__ ', '__str__', '__subclasshook__', '__weakref__, 'attr', 'one', 'show', 'tree', 'two'] Išlaikant pačią klasę ['__class__', '__delattr__', '__dic , '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', __'_, ___'_ ,' modulis 'paroda' , „trys“, „du“]
Naudojant getmembers() metodą
Kitas būdas rasti atributų sąrašą yra naudoti modulį apžiūrėti . Šis modulis suteikia metodą, vadinamą gauti nariai () kuris grąžina klasės atributų ir metodų sąrašą.
Pavyzdys:
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)> |
Išvestis:
first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second') Naudojant __dict__() magijos metodą
Norėdami rasti atributus, taip pat galime naudoti magijos metodą __diktuoti__ . Šis metodas grąžina tik egzempliorių atributus.
Pavyzdys:
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())> |
Išvestis:
first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2]) Naudojant vars() funkciją
Norėdami rasti atributus, taip pat galime naudoti vars() funkciją. Šis metodas grąžina nurodyto objekto egzempliorių atributų žodyną.
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))> |
Išvestis:
first second third 2 {'attr': 2}