How to make this class usable?

Asked

Viewed 52 times

2

In the code below, I would like to return an instance of the class itself with the data filled through a text file. The lines are stored this way in the file:

Yug Sekwaf,13-04-1570,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22

The function sanitize() if it is a function to filter the data in the text file, returning only strings with dots, as if they were floats.

class Athlete:
    def __init__(self,aName,aDob=None,aTime=[]):
        self.name=aName
        self.dob=aDob
        self.time=aTime
    def openFile(self,fileName):
        try:
            with open(fileName) as f:
                self.data=f.readline()
                self.templ=self.data.strip().split(',')
        except IOError as ioerr:
            print('Erro na Leitura dos Dados'+str(ioerr))
            return(none)
        try:
            self.name=self.templ.pop(0)
            self.dob=self.templ.pop(0)
            self.time=str(sorted(set([sanitize (t) for t in self.templ ])))
        except ValueError as valerr:
            print('Erro na atribuição dos valores'+str(valerr))
            return(none)
        return self.__class__(self,self.name,self.dob,self.time)

I would like to make the variables private, and whether it is possible to make the method openFile() static.

  • 1

    Welcome to Stackoverflow in English. I edited your question to remove the greetings as we usually keep the text as clean as possible to focus on your scheduling question. Don’t forget to do the [tour] to understand how the site works. We also deal with questions, rules and procedures in [meta] :)

1 answer

1


When you create a class in Python you have the option to create 3 types of methods: Instance methods, class methods and static methods. Let’s get to the differences between them.

Instance methods (instance methods)

They are the most common and work on the object/instance of that class. You need to set the first parameter to be self, because internally the object reference will be passed in this first parameter. Example:

class Teste:
    def __init__(self, aName):
        self.name = aName
    def exibir_nome(self):
        print('Nome: ' + self.name)

t = Teste('João')
# A referência ao objeto t é passada internamente como o primeiro parâmetro da função.
t.exibir_nome()

Class methods (class methods)

This type of method does not receive the object as a "hidden" parameter, but rather the class being used. It is useful to create alternative constructors, because with this type of method it is possible to return a new object of the same class. To define a method as class method it is necessary to use the decorator @classmethod (documentation) and define cls as the function’s first parameter. Example:

class Teste:
    def __init__(self, aName):
        self.name = aName

    @classmethod
    def criar_maria(cls):
        return cls('Maria')

t = Teste('João')
# Criará outro objeto da classe Teste já com o nome "Maria" definido.
m = Teste.criar_maria()

Static methods (Static methods)

This type of method does not receive any "hidden" parameter, nor self and neither cls, is like a normal function within the class. To define a static method it is necessary to use the decorator @staticmethod (documentation). Example:

class Teste:
    def __init__(self, aName):
        self.name = aName

    @staticmethod
    def metodo_estatico(x):
        print(x)

t = Teste('João')
Teste.metodo_estatico(123)

Note that in the examples I called class and static methods using the class name:

m = Teste.criar_maria()
Teste.metodo_estatico(123)

But it is also accepted by the language to call them from the object:

m = t.criar_maria()
t.metodo_estatico(123)

However, the instance method needs to be called through an object, if we try to call an instance method using the class name it will give error. Unless we manually pass the hidden parameter, which is precisely the object:

Teste.exibir_nome()  # Essa linha daria erro.
Teste.exibir_nome(t) # Essa linha seria aceita.

For what you want you should use then one class method, and not a static method, because you want your method openFile() return a new class object Athlete. And to create local variables, within this method, just use the direct name of the variable, without the self.

Your class would look like this, so:

class Athlete:
    def __init__(self, aName, aDob=None, aTime=[]):
        self.name = aName
        self.dob = aDob
        self.time = aTime

    @classmethod
    def openFile(cls, fileName):
        try:
            with open(fileName) as f:
                data = f.readline()
                templ = data.strip().split(',')
        except IOError as ioerr:
            print('Erro na Leitura dos Dados' + str(ioerr))
            return(None)
        try:
            name = templ.pop(0)
            dob = templ.pop(0)
            time = str(sorted(set([sanitize(t) for t in templ])))
        except ValueError as valerr:
            print('Erro na atribuição dos valores' + str(valerr))
            return(None)
        return cls(name, dob, time)

Sources:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.