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:
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] :)
– Barbetta