[Python] If a default parameter of a method should belong to self (eg: parameter_name =...

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Using self.xxxx as a default parameter - Python

    edit: After reviewing, I found that the process I mentioned doesn't work. However, I've found that if the global variable is a list, I can modify the default parameter post definition by changing the contents of the list (presumably because the variable is now a reference to data, instead of data itself). Does this have an issue that makes it a bad option?

    In the link above, the answer to how to make a default parameter belong to self was to instead make it equal to None, then test for None within the method. This was because default parameters are defined at definition rather than execution, and thus the attribute doesn't even exist yet. (At least, that was my understanding.)

    My question is: why not make it equal to a global variable with an initially arbitrary value? The global variable can then be modified post definition, making the default parameter capable of belonging to self. I don't know if I explained that well, so here's sort of what I'm thinking.

    param = None

    class Example()
    def __init__(self):
    self.x = 7
    global param
    param = self.x

    def method(self, default = param):
    print(default)

    Continue reading...

Compartilhe esta Página