Una classe és un pla o prototip definit per l'usuari a partir del qual es creen objectes. Les classes proporcionen un mitjà per agrupar dades i funcionalitats. La creació d'una nova classe crea un nou tipus d'objecte, que permet crear noves instàncies d'aquest tipus. Cada instància de classe pot tenir atributs associats per mantenir el seu estat. Les instàncies de classe també poden tenir mètodes (definits per la seva classe) per modificar el seu estat.
Exemple:
Python 3
# 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)> |
>
>
Sortida:
COE COE Shivam Sachin COE>
Nota: Per a més informació, consulteu Classes i objectes de Python .
Obtenció d'una llista d'atributs de classe
És important conèixer els atributs amb els quals estem treballant. Per a dades petites, és fàcil recordar els noms dels atributs, però quan es treballa amb dades grans, és difícil memoritzar tots els atributs. Afortunadament, tenim algunes funcions a Python disponibles per a aquesta tasca.
Utilitzant la funció dir() integrada
Per obtenir la llista de tots els atributs, mètodes juntament amb alguns mètodes màgics heretats d'una classe, utilitzem un sistema integrat anomenatvostè().
Exemple:
Python 3
configuració del navegador d'Internet
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))> |
>
>
Sortida:
primer segon terç 2 En passar l'objecte de la classe ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '_,_gt_' '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__new__', '__reduce__', '__reduce_ex__', '__reduce_ex__', '__'_rep, '__'_rep, '__'_rep, '___'___ ', '__str__', '__subclasshook__', '__weakref__', 'attr', 'one', 'show', 'three', 'two'] Passant la mateixa classe ['__class__', '__delattr__', '__dict__' , '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass___', '_, '___', '__le __module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__subclasshook__', '__'hook', '_'hook', '_'how , 'tres', 'dos']
Utilitzant el mètode getmembers().
Una altra manera de trobar una llista d'atributs és utilitzant el mòdulinspeccionar. Aquest mòdul proporciona un mètode anomenatgetmembers ()que retorna una llista d'atributs i mètodes de classe.
Exemple:
Python 3
Com puc trobar aplicacions amagades a Android
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)> |
>
>
Sortida:
first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second')> Utilitzant el mètode màgic __dict__().
Per trobar atributs també podem utilitzar el mètode màgic__dicte__. Aquest mètode només retorna atributs d'instància.
Exemple:
Python 3
matriu java
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())> |
>
>
Sortida:
first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2])> Utilitzant la funció vars().
Per trobar atributs també podem utilitzar la funció vars(). Aquest mètode retorna el diccionari d'atributs d'instància de l'objecte donat.
Python 3
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))> |
>
>
Sortida:
first second third 2 {'attr': 2}>