1

I want to make it so x is only global within the class.

I have tried using self.x but that does not seem to work. I could be doing it wrong though.

class Test:

   def __init__(self):
      pass

   def test1(self,number):
      global x
      x = number
      print(x)

   def whereIwantToRedefineIt(self):
      print(x)


Test().test1(2) #<------ Making output 2

x=200 #<-------------- It should not be able to redefine the variable

Test().whereIwantToRedefineIt() #<-------- I want to make this output 2

I want to make the function "whereIwantToRedefineIt" not be affected by the "x=200" which is outside the class. I want it to output 2

2 Answers2

0
class Test:

  def __init__(self):
      self.x = None
  def test1(self,number):
      self.x = number
      print(x)

   def whereIwantToRedefineIt(self):
      print(self.x)

You can get the desired result if you invoke the methods on the same instance.

test = Test()
test.test1(2)
test.whereIwantToRedefineIt() # This will print 2
gipsy
  • 3,859
  • 1
  • 13
  • 21
0

The closest thing is a class variable, which can be accessed by prefixing the variable name with the class name:

class MyClass:
    somevar = 0
    def somemethod(self):
        print(MyClass.somevar)
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42