Why is it necessary to instantiate a Python class when I can call it directly?

Asked

Viewed 99 times

2

class People:
    def talk():
         print('hello')

p1 = People
p1.talk()

What is the need of instance it if I may call you directly?

class People:
    def talk():
         print('hello')

People.talk()

2 answers

5

First, classes are not required in some cases, even if people use where they don’t need to.

Classes should create the object model that serves for something useful, so it needs to be very well defined before coding. If you’re making a class that doesn’t make sense, then you don’t have to create a class. Understand What is the difference between a class and an object?. If you won’t create objects you don’t need a class.

In some cases it is possible that you wanted something encapsulated in the class and not in the object, so this is allowed. It is more or less rare to need it correctly (many people use it incorrectly). There are cases of having a utilitarian methods that are independent of the state of the object, there makes sense.

Artificial examples are not useful for appender programming, especially in object orientation, only the real case can determine what is right to do. Artificial examples are useful if they are good examples to show a mechanism, but never how to use it properly.

This example is just a mistake, it’s an artificial example that doesn’t make something useful, so it can’t be considered for learning.

The code defines a model for an object, it only has one method within the class, so there shouldn’t be a class there. This being wrong, just don’t make a code like this.

If the example were good, it solved a real problem then we could discuss it better. And in fact it has already been done in:

So this case works by coincidence, because whatever, it’s not creating something real. If you had a real method, that is, if you had a method with self, how could call this method passing the self without creating an instance before? Then we have a case that the class makes sense and needs to instantiate.

In an extremely simplified way making a class that makes sense and uses the self:

class People:
    nome = ""
    def __init__(self, nome):
        self.nome = nome
    def talk(self):
         print('Meu nome é ' + self.nome)

p1 = People("joão")
p1.talk()

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Now that you have a real class try to access without instantiating.

4


You didn’t charge anything

In doing p1 = People, you have not created a class instance People. In fact you did that p1 receive the class itself People, see:

class People:
    def talk():
         print('hello')

# p1 é a própria classe People
p1 = People

print(p1 == People) # True
print(type(People)) # <class 'type'>
print(type(p1))     # <class 'type'>

# p1 é uma instância de People? Não
print(isinstance(p1, People)) # False

To create an instance of People, you would have to call People() (with the parentheses), see the difference:

# agora sim estou criando uma instância de People
p = People()

# p não é a própria classe People
print(p == People) # False
print(type(p))     # <class '__main__.People'>

# p é uma instância de People? Sim
print(isinstance(p, People)) # True

That’s why in your example, p1.talk() is the same as People.talk(), since the value of p1 is the class itself People.


As for the fact that you are using a class for this case, it makes sense, etc., besides the right way to do, the other answer already said everything.

Browser other questions tagged

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