How do I access an attribute(which is a list) of a class by a method outside that class in python?

Asked

Viewed 39 times

2

I have a Shop class that one of her attributes is a list (self.products = [ ]).

class Loja(Empresa):
    def __init__(self, nome, cnpj, razao_social):
        super().__init__(nome, cnpj)
        self._razao_social = razao_social
        self._funcionarios = []
        self._clientes = []
        self.produtos = []

Outside of this class I have a method def report that receives as parameter a type of product (electronic, food etc) and goes through this list of products and prints the names of the products.

def relatorio(tipo_produto):
    for i in Loja.produtos:
        if isinstance(tipo_produto, Produto):
            print(i)

The problem is that this way I did not work, the pycharm returns an error saying that "the Store object type was not assigned to Products". If you can help, I really appreciate it.

  • 1

    self.produtos is not an attribute of its class, it is an attribute of instances that you create from the class. You cannot access Loja.produto because this value does not exist at the class level, only of the instances created from it. The correct one would be to initialize an instance of Loja with something like minha_loja = Loja(nome='Supermercado', ...) and then access the attribute minha_loja.produtos.

  • If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

1 answer

2

Well, if you define the method within the class, which seems more natural to me, just do:

self.produtos

Within the class definition, whenever you want to call a hypothetical instance of the class you use the key-word self.

However, as you’re using it outside, I believe you made a conceptual mistake by not assimilating the difference between class and instance.

The class is a "factory" of objects of a certain type, it is not the object itself. So if you want to use a class object in a function outside the class, you need to instantiate the object first.

Here is a simplified example:

class Loja:
    def __init__(self, nome, cnpj, razao_social, produtos, funcionarios=50, clientes=50):
        self._razao_social = razao_social
        self._funcionarios = funcionarios
        self._clientes = clientes
        self.produtos = produtos

def relatorio(tipo_produto):
    for i in tipo_produto.produtos:
        print(i)

tipo_produto = Loja("Loja 1", cnpj=18299201, razao_social = "Nossa Firma", produtos = "anv bhs kok sijs".split(' '))

print(relatorio(tipo_produto))

Ouput:

anv
bhs
kok
sijs

Browser other questions tagged

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