-2
print("Hello World")
class testing:

  params = 1
  print(params)

  #@classmethod
  def __init__(self, params):
    self.params = params

  print(params)
b = testing(params = 5)

Output:

Hello World 
1
1

How do I get changed values of params using __init__ or any other function while keeping params as class variable?

martineau
  • 119,623
  • 25
  • 170
  • 301
runaway57
  • 5
  • 4

2 Answers2

1

The same way you assign it. self.params is a class-level variable, meaning you can manipulate and call it using self.params. In the lines of code:

params = 1
print(params)

params is a different variable than self.params, defined later. To print that, you would write:

print(self.params)

somewhere after your __init__() function wherein it was defined.

GetHacked
  • 546
  • 4
  • 21
0

Is this what you want? The __init__ method directly changes the class variable.

print("Hello World")


class testing:
    params = 1
    print(params)

    # @classmethod
    def __init__(self, params):
        # self.params = params
        testing.params = params


b = testing(params=5)
print(testing.params)
Hermis14
  • 214
  • 3
  • 12