Una clase es un modelo o prototipo definido por el usuario a partir del cual se crean objetos. Las clases proporcionan un medio para agrupar datos y funcionalidades. La creación de una nueva clase crea un nuevo tipo de objeto, lo que permite crear nuevas instancias de ese tipo. Cada instancia de clase puede tener atributos adjuntos para mantener su estado. Las instancias de clase también pueden tener métodos (definidos por su clase) para modificar su estado.
Ejemplo:
Python3
matriz ordenada en java
# 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)> |
>
>
Producción :
COE COE Shivam Sachin COE>
Nota: Para obtener más información, consulte Clases y objetos de Python .
Obtener una lista de atributos de clase
Es importante conocer los atributos con los que estamos trabajando. Para datos pequeños, es fácil recordar los nombres de los atributos, pero cuando se trabaja con datos grandes, es difícil memorizar todos los atributos. Por suerte, tenemos algunas funciones en Python disponibles para esta tarea.
Usando la función dir() incorporada
Para obtener la lista de todos los atributos, métodos junto con algunos métodos mágicos heredados de una clase, utilizamos un integrado llamadotú().
Ejemplo:
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))> |
>
>
Producción :
primero segundo tercero 2 Pasando objeto de clase ['__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', 'tres', 'two'] Pasando la clase misma ['__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__', 'one', 'show' , 'tres dos']
Usando el método getmembers()
Otra forma de encontrar una lista de atributos es usando el móduloinspeccionar. Este módulo proporciona un método llamadoobtener miembros()que devuelve una lista de atributos y métodos de clase.
Ejemplo:
java invirtiendo una cadena
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)> |
>
>
Producción :
first second third 2 ('attr', 2) ('one', 'first') ('three', 'third') ('two', 'second')> Usando el método mágico __dict__()
Para encontrar atributos también podemos usar el método mágico.__dict__. Este método solo devuelve atributos de instancia.
Ejemplo:
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())> |
>
>
Producción:
first second third 2 {'attr': 2} dict_keys(['attr']) dict_values([2])> Usando la función vars()
Para encontrar atributos también podemos usar la función vars(). Este método devuelve el diccionario de atributos de instancia del objeto dado.
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))> |
borrado de caché npm
>
>
Producción:
first second third 2 {'attr': 2}>