0

A value can be assigned to a class variable from within an instance method of the same class with the following notation -

 [class name].[class variable name] = [value]

for example -

In [104]: class MyClass: 
     ...:     """A simple example class""" 
     ...:     i = 12345 
     ...:  
     ...:     def f(self): 
     ...:         MyClass.i = 5 
     ...:         return 'hello world'                                                               

In [105]: MyClass.i                                                                                  
Out[105]: 12345

In [106]: MyClass().f()                                                                              
Out[106]: 'hello world'

In [107]: MyClass.i                                                                                  
Out[107]: 5

Can this be achieved without hard coding the class name?

user2309803
  • 541
  • 5
  • 15

1 Answers1

0

You can do this with self.__class__ attribute

>>> class A:
...     def f(self):
...         print(self.__class__)
...
>>> A().f()
<class '__main__.A'>