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!
self.use_variable = lambda x=self.variable:print(x)
inside your__init__
, that way you can have it as an optional argument – Krysta