Error instantiating objects in python OO

3

Well, I'm going to gather two doubts about python OO here in this message. I use anaconda (python 3.6.1).

I'm trying to make a little project to study object orientation in python 3.6.1. Initially, the problem is in passing the parameters to the constructor.

# coding: UTF-8
from automovel import Veiculo

class Veiculo(object):

    #como atribuo valores de instância para essas variáveis como no java, por exemplo?

    placa=None
    cor=None
    cidade=None

    #construtor

    def __init__(self, placa, cidade, cor):
        self.placa=placa
        self.cor=cor
        self.cidade=cidade

    # a linha abaixo não dá erro, mas não usa o construtor
    carro=Veiculo

    # a linha abaixo dá erro e nem usa o construtor
    carro2 = Veiculo("JFW3128", "Salvador", "preto")

The error:

  

Description Resource Path Location Type   Unresolved import: Vehicle automovel.py / automoveis line 7 PyDev Problem

Without the import line, it gives the error:

  

Description Resource Path Location Type   Undefined variable: Vehicle automovel.py / automoveis line 13 PyDev Problem

Note, the filename is automovel.py. I use the eclipse IDE with pydev installed.

I know there are so many theories in OO, like in the link:

Attribution and OO in Python

I prefer to stick to the concrete part anyway.

In this link, it seems to me that python OO works quietly (python v2):

Print a list of objects as a string in Python

Already the same question below was not a return of user satisfaction:

Problem instantiating classes in Python 3

    
asked by anonymous 09.03.2018 / 18:03

2 answers

2

You are thinking a lot "very". This code can be pythonized.

In python, what defines the scope is the indentation.

For example:

def function(a):
    if a is None:
        b = 100
        return b

    if a > 300:
        c = 90
        return a + c

    #erro, b e c não estão definidas nesse escopo.
    # b só pode ser referenciada dentro do primeiro if.
    # c só pode ser referenciada dentro do segundo if.
    return c*b*90

In your case, your Veiculo class has within its scope everything that is indented with four spaces or a tab, which are:

  • The variables you set: placa , cor and cidade .
  • The constructor: def __init__(self, placa, cidade, cor) .
  • And calls: carro=Veiculo and carro2 = Veiculo("JFW3128", "Salvador", "preto")

First, you do not need to declare the variables before assigning some value to them. That is, it is useless to do this:

placa=None
cor=None
cidade=None

You do not have to extend Veiculo to Object . It's the same thing to do: class Veiculo:

Whenever you give self.attr you will be creating an attribute of the class, if it does not already exist. According to PEP8 , all attributes of the class must be created in the constructor. That is, their first statement must be in __init__ . At that point, your code is right.

You do not need to import a module if you already have access to it. So it's also useless to do the import you've made.

Pythonized code:

class Veiculo:

    def __init__(self, placa, cidade, cor):
        self.placa = placa
        self.cor = cor
        self.cidade = cidade

    def __str__(self) -> str:
        return "({0};{1};{2})".format(self.placa, self.cor, self.cidade)


if __name__ == "__main__":
    carro = Veiculo
    carro2 = Veiculo("JFW3128", "Salvador", "preto")
    print(carro)
    print(carro2)

Because if __name__ == "__main__": ?

The python interpreter runs all the code as it reads. If for some reason in another file you give from automovel import Veiculo and do not have this check of the variable __name__ it will execute that part of the code without you having called python automovel.py . That is, it will only execute this part of the code so the script execution is done by python automovel.py .

    
24.03.2018 / 21:58
3

There are two problems there. Let's break it down, first remove this line from import and remove the indentation from the variable car and car2:

class Veiculo(object):

    placa=None
    cor=None
    cidade=None

    #construtor

    def __init__(self, placa, cidade, cor):
        self.placa=placa
        self.cor=cor
        self.cidade=cidade

# Se as linhas abaixo estiverem indentadas como estavam inicialmente,
# ou seja, no mesmo nível de Veiculo,
# significa que as variáveis fazem parte da classe Veiculo, e você
# não vai conseguir declarar uma var Veiculo dentro dele mesmo

carro = Veiculo
carro2 = Veiculo("JFW3128", "Salvador", "preto")

You can now cut the car and car2 variables and save the file only with the Vehicle class, and then import it into another file, and paste the car and car2 lines into this new file

    
23.03.2018 / 08:52