0
class Example:
    text = "Hello World"

    def function():
        print(text)

Example.function()  

Example.printText() throws this error NameError: name 'text' is not defined

Why doesn't printText() remember the class attribute text?
Does it have something to do with order python interprets the code?

Kun.tito
  • 165
  • 1
  • 7

2 Answers2

0

function is static you need to use self to access the object property like this:

    class Example:
    text = "Hello World"

    def function(self):
        print(self.text)

if you want to keep it static use:

def function():
    print(Example.text)


class Example:
    text = "Hello World"
0

use @staticmethod decorator to make the function static.

class Example:
    text = "Hello World"
    
    @staticmethod
    def function():
        # print(self.text) # raises error
        # because self is not defined
        # when using staticmethod
        
        # so you need to specify
        # the class name
        print(Example.text)

        
# now its working
>>> Example.function()  

out

Hello World

extra information:

  • variable text will be available for every object created using this class, and if you change text, will be changed in every object of the class.
alexzander
  • 1,586
  • 1
  • 9
  • 21