Home > Back-end >  How to access a variable from constructor outside of method in python
How to access a variable from constructor outside of method in python

Time:07-23

class A(): 
   B: str = "no"
class test(A): 
   a = None
   def __init__(self): 
       self.a = "test"
   
   if self.a == "test":
      B = "yes"
t = test()
print(t.B)
NameError: name 'self' is not defined

self.a shows an error so how can I access a which was assigned a value in the constractor out side of a method inside the class?

CodePudding user response:

What you are asking for (given that your example defines an instance attribute) is quite frankly not possible, you can't access an instance attribute without referencing that instance and you can't reference an instance of a class in its body.

What could be done is changing the class attribute from the constructor but that would be pointless because all code in the body of the class gets executed first so such a check (as in your provided sample) would be pointless anyways.

CodePudding user response:

  1. Because you are making class object u need to define the object name used
class test():
    def __init__(self):
  1. You want to access your attribute, you cant access outside of method so
class test():
    def __init__(self):
        self.a = "test"
        if self.a == "test":
            pass

or you can create another method that process that

class test():
    def __init__(self):
        self.a = "test"
        self.access_a()
                
    def access_a(self):
        if self.a == "test":
            print("do something")
            pass
  • Related