简体   繁体   中英

how should i access a class variable from another class in python?

I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().

Class A:
    def __init__(self):
        ---some code---
    def email_id(self):
        self.email = x

Class B:
    def __init__(self):
        print(A().email)

I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().

Class A:
    def __init__(self):
        ---some code---
    def email_id(self):
        self.email = x

Class B:
    def __init__(self):
        print(A().email)

I think what you might be looking for are property decorators

Class A: 
    def __init__(self): 
        ---some code--- 
    @property
    def email(self): 
        return (some code to show the email)

The field email of class A is created when email_id() is called. Therefore, by the time print(A().email) is executed, this field is still not set.

You can set it first

Class B:
    def __init__(self):
        a = A()
        a.email_id("email")
        print(a.email)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM