-2
class A:
    def __init__(self):
       self.name="XYZ"
    def collect_data(self):
        b=B.age 
        print(b)

class B:
    age=9

objectA=A()
objectA.collect_data()

Please tell me if this the correct way of accessing the static variable present in class "B" from class "A" . Also I would like to know had there been a static method in class "B" , would I be able to access that in any way from class A .

DavidG
  • 24,279
  • 14
  • 89
  • 82

1 Answers1

0

Accessing the static variable as you do is correct and you do access static methods in a similar way, I've updated your example code to do this below.

class A:
    def __init__(self):
       self.name="XYZ"
    def collect_data(self):
        b=B.age 
        print(b)
        B.static_method_b(10)

class B:
    age=9

    @staticmethod
    def static_method_b(val):
        print(val)

objectA=A()
objectA.collect_data()
Luke Smith
  • 893
  • 4
  • 8
  • Hey thanks Luke ! just one more question . Can this static variable be private ? suppose in Class B , it is __age=9 . Then how do I get to access from class A ? is it like B.__age=9 ? – Ankit Biswas Nov 02 '17 at 13:42
  • @AnkitBiswas that is a bit more complicated, but someone has already explained it [here](https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes) – Luke Smith Nov 02 '17 at 15:49