How do I make a variable in my class global but only make it global within the class?

Atomization

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

gipsy
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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I make 2 comparable methods in only one class?

How do I make a constructor available to only the factory class?

How do I make a method in my Java class return findViewById?

How Do I Make Hidden Property In Base Class Get Only

How to make global class var in the class method

Python: Change: How do I make local variable global?

make variable from global scope available to class after import

How do I make the global type context variable in flutter?

How do I make the class variable equal to my textbox value while converting to int32

How can I make a global variable in axios?

How can I make variable global in View?

Make global instance of class - JAVA

How can I create a Global FileInputStream object, which will be available to access from other class within in my project?

How do declare global variable in PHP class

How do I make an array of linked lists as a variable for my java class?

How do I make my JFrame class my main class?

How do I make inheritable class variable?

How to make my db variables global for my class (php)

How do I make a variable created inside a function become global?

how to make a variable global only in one place

Python: make class method global

Python global variable within function within class

React Native - How to make a variable global from my fetch method

How do I make Typescript recognize my custom global filter?

Call global variable within a class

Why do I have to make the variable global?

How can i make a method available only from within the class

How do I make a protocol that my generic class can conform to?

How to make a global variable in sveltekit?