0

when I try to use x in method , error is resulted saying " 'x' is not defined"

class main:
    x=20
    def __init__(self):
        pass

    def func(self):
        z=x+10
        print(z)

obj1=main()
obj1.func()

3 Answers 3

3

You can use it through self:

class main:
    x=20
    def __init__(self):
        pass

    def func(self):
        z=self.x+10
        print(z)

obj1=main()
obj1.func()

or through self.__class__

class main:
    x=20
    def __init__(self):
        pass

    def func(self):
        z=self.__class__.x+10
        print(z)

obj1=main()
obj1.func()

or through class name:

class main:
    x=20
    def __init__(self):
        pass

    def func(self):
        z=main.x+10
        print(z)

obj1=main()
obj1.func()
Sign up to request clarification or add additional context in comments.

Comments

0
class main:
    x=20
    def __init__(self):
        pass

    def func(self):
        z=self.x+10
        print(z)

obj1=main()
obj1.func()

I always perfer the code goes as the following, to init the value in constructor method.

class main:

    def __init__(self):
        self.x = 20

    def func(self):
        z=self.x+10
        print(z)

obj1=main()
obj1.func()

Comments

0

Change the first line of func to

  z = self.x + 10 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.