Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create classes on Python?

Tags:

python

I'm learning the basics of python on classes and objects.

I have created a basic class object with getters, setters and __str__ function.

'''
Created on 02/06/2012

@author: rafael
'''

class Alumno(object):
    '''
    Esta clase representa a un alumno de la ibero
    '''
    __nombre=None
    __idAlumno=None
    __semestre=0

    def __init__(self,nombre,idAlumno,semestre):
        '''
        Constructor
        '''
        self.__nombre=nombre
        self.__idAlumno=idAlumno
        self.__semestre=semestre

    def Alumno(self):
        return self

    def getId(self):
        return self.__idAlumno
    def setId(self,idAlumno):
        self.__idAlumno=idAlumno
    def getNombre(self):
        return self.__nombre
    def setNombre(self,nombre):
        self.__nombre=nombre
    def getSemestre(self):
        return self.__semestre
    def setSemestre(self,semestre):
        self.__semestre=semestre

    def __str__(self):
        info= "Alumno: "+self.getNombre()+" - id: "+self.getId()+" - Semestre:"+str(self.getSemestre())
        return info

And a python module that imports that class and initialize the object for print their info.

'''
Created on 02/06/2012

@author: rafael
'''
from classes import *

if __name__ == '__main__':
    alumno=Alumno("Juanito Perez","1234",2)
    print alumno

But I'm having a NameError Exception, so I must create my object in this way:

alumno=Alumno.Alumno(param,param,param)

But I want to be on this way:

alumno=Alumno(param,param,param)

Can someone explain to me how classes work or what I'm doing wrong?

like image 743
Rafael Carrillo Avatar asked Oct 27 '25 06:10

Rafael Carrillo


1 Answers

Ah, welcome to the issue of python namespace verbosity.

Unlike Java, where if you have a class named Foo in a file Foo.java, your class is not automatically hoisted into the module namespace.

If you want this behavior, you will need to do:

from Alumno import Alumno

There are other difficult ways around this. If for example you have a directory:

package/
    ...
        submodule/
            YourClass.py
            YourClass2.py
            __init__.py

You can do from YourClass import YourClass in __init__.py. Thus outside of the submodule, you can do import submodule.YourClass or from submodule import YourClass and get your desired behavior.

like image 87
ninjagecko Avatar answered Oct 28 '25 19:10

ninjagecko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!