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: