Is there any way to pass a class instance as a parameter of a Python method?

Asked

Viewed 1,648 times

1

I’m doing an implementation of the Star algorithm(A*).

My doubt is just that of the title, I come from java and c++, and I do not know how to do this in python.

def transfTo(Bucket a): <------------Dúvida aqui!
        transf = a.total - a.current
        if current >= transf:
            a.current = a.total
            current -= transf
        else:
            a.total += current
            current = 0
  • The question is whether you can pass as parameter or whether it is possible to define the instance class? Remember that, unlike Java and C++, Python has dynamic typing.

  • If I can pass as parameter. Because I am not able to access the methods and attributes of the variable "a" of the Bucket class.

1 answer

1


Yes, the difference is that in python typing is dynamic, it comes from Duck Typing

Follow an example by passing a class as parameter

class Pessoa:
    def __init__(self):
        pass

    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

def meu_metodo(pessoa):
    print(pessoa.getNome())
    print(pessoa.getIdade())

def meu_outro_metodo():
    pessoa = Pessoa()
    pessoa.setNome("Leonardo")
    pessoa.setIdade(23)
    meu_metodo(pessoa)


meu_outro_metodo()

In the example above, there is a class, In the first method the class is "instantiated" and has its values set, after which another method is called, passing the class in the parameter, and in this other method, the values are printed

Browser other questions tagged

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