Calling attributes of an object in another class in python

Asked

Viewed 4,127 times

3

I’m a beginner in python and I wanted to know what I call attributes of another object in another class, because in Java, for example:

package model;
import java.util.ArrayList;
import java.util.List;

public class FuncionarioDAO {
    Produto p;   // Essa linha... como faço isso em python?


    List<Produto> itens = new ArrayList<Produto>();


    public void Cadastrar(Produto p) {
        itens.add(p);
    }

    public void Remover(int codigo) {
        for(int i=0; i<itens.size(); i++) {
            Produto p = itens.get(i);
                if(p.getCodigo() == codigo) {
                    itens.remove(i);
                    break;
                }
           }
      }

     public void Alterar(Produto p) {
         Remover(p.getCodigo());
         Cadastrar(p);   
         }
}

I also have another question, I have basis of POO, only that I do not understand very well the database interconnection with the application.

There comes a time when I need to pass the data to SQL and I don’t know what to do.

Someone could give me tips?

  • 1

    You have asked more than one question and one of them can be answered at this link http://pythonclub.com.br/gerenciando-banco-dados-sqlite3-python-parte1.html

  • We didn’t miss an Inject in this product ? @Inject Product p; ?

  • but how do you do it in python? because I have tested it this way and it is wrong

  • I’m drafting an answer

3 answers

2

For example in a file called person.py, you have the People class and want to call it in a main.py file

main py.

class Usuario:
    def __init__(self):
        self.pessoa = Pessoa()

If you want to call in a function of your new file:

class Usuario:
    def minha_funcao(self):
        pessoa = Pessoa()

2

Note the following example:

example.py

class Pessoa:

    def __init__(self, nome, idade):
        self.nome = nome
        self.idade = idade

    def setNome(self, nome):
        self.nome = nome

    def setIdade(self, idade):
        self.idade = idade

    def getNome(self):
        return self.nome

    def getIdade(self):
        return self.idade

To gain access to the object, its attributes and methods, simply import it into the class you want:

main py.

from exemplo import Pessoa

pessoa = Pessoa('Roberto', '12')

pessoa.setNome('Paulo')
pessoa.setIdade('18')

print('O ' + pessoa.getNome() + ' possui ' + pessoa.getIdade() + ' anos.')


To learn more about the Imports follows this website.
There are different ways to import a class or a object :

from modulo import objeto // Trará apenas o objeto requerido
from modulo import objeto as ob // Trará o objeto com o nome de 'ob'
from modulo import * // Importa todas as classes do módulo.


Your second question refers to the persistence of data using Python. For this the most common way is to use ORM of English : Object-Relational mappers , which are frameworks responsible for transposing the codes sql for objects that can be used within the chosen language. Hibernate is an example of ORM for java that is very well known in the middle. Ja for Python one of the best known is the SQL Alchemy.

Useful links:

  • In the class definition Person seems to have indentation flaws. And preferred to use setters/getters to Property for some specific reason?

  • 1

    I used setters and getters because Rafaela cited an example in java, demonstrating a previous knowledge of the language. I thought it valid to use them to approximate the example given to her experience.

1

I wanted to know what I call attributes of another object in another class

The line you highlighted is declaring an attribute of the class. In Python, the statement is made in the first assignment. If you want to ensure that an attribute is created before receiving a specific value, state it as None within the __init__.

class Teste():
    def __init__(self):
        self.p = None

i do not understand very well the database interconnection with the application.

This is too comprehensive to fit an answer.

Someone could give me tips?

Search Sqlalchemy tutorials.

Browser other questions tagged

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