1

I am very new to python and especially OOP. Pardon if this comes along as a silly question. Say if I have a class called X and two functions / methods within it (a and b).

var1 = "Amazon"
class X() :
  def a(var1) : 
    ........
    ........
  def b(var1)
    ........
    ........

When I try to declare var1 outside the class, it is not passing the expected value to the methods a and b. I tested it by running my code. Is there any way to pass a singular argument across multiple methods within a class ? Kindly help. Thank you.

  • Use it directly without passing it into the arguments. https://www.w3schools.com/python/python_variables_global.asp – Sau1707 Jul 09 '22 at 08:59
  • No luck yet. I'll go through the doc and try again. –  Jul 09 '22 at 09:04
  • @Sau1707 Update : It is working without passing the arguments but for some reason, it is not taking the correct value when I try to get the global variable's value using input() function. Any idea how that might work ? –  Jul 09 '22 at 09:10
  • @UnholySheep It is working without passing the arguments but for some reason, it is not taking the correct value when I try to get the global variable's value using input() function. Any idea how that might work ? –  Jul 09 '22 at 09:11

1 Answers1

1

If you have to pass is as an argument, you can set is as a default value like so:

var1 = "Amazon"
class X:
  def a(myvar=var1): 
    ........
    ........
  def b(myvar=var1):
    ........
    ........

Or even in the class init method, if you have one:

var1 = "Amazon"
class X:
    def __init__(myvar=var1):
        self.myvar = myvar

Then use it in the class methods with self.myvar

nir
  • 46
  • 2