How to make this class usable?

2

In the code below, I would like to return an instance of the class itself with the data filled in 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() is a function to filter the data in the text file, returning only strings with points, as 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 know if it is possible to make the method openFile() static.

    
asked by anonymous 13.11.2018 / 01:54

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 face 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 that 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 for creating 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 a class method, you must use the @classmethod ( documentation decorator) and set cls as the first parameter of the function. 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" parameters, neither self nor cls , is like a normal function within the class. To define a static method, you must use the @staticmethod ( documentation decorator). 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 the static and class methods using the class name:

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

But it is also accepted by the language calls 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 just the object:

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

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

Your class would look like this, then:

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:

     
    
13.11.2018 / 05:13