Python: Why can't you use a self.variable as an optional argument in a method?
Asked Answered
V

2

5

I have created a class where I wanted to pass an self.variable into an optional argument within a method. The reason being because I want to store information in the Self.variable made in an other method, However, If I use the method I would like to have to option to override the self.variable with my own manual information.

Sadly, this is not allowed, therefore I was wondering why not!? Also, I was wondering if someone knows a Pythonic way to achieve the same objective?

This is an example of what I tried:

# example:

class Example(Object)

    def __init__(self):
        self.variable = []

    def fill_variable(self):
        self.variable = [random.randint(1,10)] * 10

    def use_variable(self, random_numbers = self.variable)
        print(random)

test.Example()
test.fill_variable()
test.use_variable()

# or
test.use_variable(random_numbers=[1,2,3,4,5,6,7,8,9,10])

My expectation was that test.use_variable() would print 10 random numbers And that test.use_variable(random_numbers=[1,2,3,4,5,6,7,8,9,10]) would print(1,2,3,4,5,6,7,8,9,10)

Thank you for any kind help and explenation!

Valvule answered 11/6, 2019 at 3:9 Comment(0)
B
5

Unfortunately, it's impossible, instead you can use an if statement checking it it is the same value (None) if so, assign it to self.variable:

def use_variable(self, random_numbers = None):
    if random_numbers == None:
        random_numbers = self.variable
    print(random_numbers)
Bellyache answered 11/6, 2019 at 3:15 Comment(1)
or you could just do: self.use_variable = lambda x=self.variable:print(x) inside your __init__, that way you can have it as an optional argumentKrysta
C
1

The code lines at class level which include the def lines of the methods are executed at import time once. At this time there is no instance of the class that could be self and not even the class is complete yet.

An other point is that the argument name self exists inside the method only.

Cowey answered 11/6, 2019 at 3:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.