Definitions and their use in classes

Asked

Viewed 37 times

1

When I create a "def" from what I understand is different from __init__ right? If I create an object in the __init__ it is possible to access it from other def's? In some codes I noticed they use 'self.objeto' even in other defs. My question is whether when I create the object within the def it is valid for the whole class?

  • 1

    Lucas, could you edit your question and add more information? Preferably with examples of code for us to understand your problem (I confess that confused me the way it is written).

1 answer

2

Depends.

In Python you will notice that for instance methods (which are not static or class), the first parameter will always be called¹ self. This object is a reference to the very instance you are working on when the method is invoked. All class methods will have the reference to the same object and therefore any change you make to it in one method will be reflected in all others.

For example, if I do:

class Pessoa:
    def __init__(self):
        self.idade = 0

I’ll be modifying the object self defining a new field called idade and setting it to zero. If I create another method using this value:

class Pessoa:
    def __init__(self):
        self.idade = 0

    def get_idade(self):
        return self.idade

The value of self.idade will still be 0, because self will be the same object between the two methods.

However, if you do not define the values in self, these changes will only belong to the local scope. For example, instead of doing self.idade do only idade:

class Pessoa:
    def __init__(self):
        idade = 0

    def get_idade(self):
        return self.idade

The object idade will exist only in the scope of __init__ and will not exist in the get_idade.

In terms of classes and objects, whenever the value represents a new state of the object you should store it in self. If the value is auxiliary or temporary, use local variables.


¹: It is not always, because the parameter can receive any name, but by convention and 99% of the time will be self.

  • I understood the part where altering an object with self alters it for the whole class, it just wasn’t completely clear one point for me. Can I create more than one self object? For example: class person: def init(self): self.age = 0 self.sex = ' self.address = ''

  • Yes, but not the correct nomenclature. The self will be the same object, what you will be creating are fields in it and fields you can create as many as you need.

Browser other questions tagged

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