Siddanth Shaiva
Siddanth Shaiva

Reputation: 23

How to get variable from one class to another class in python

class WelcomeScreen(Screen): #welcomeScreen subclass
    def __init__(self, **kwargs): #constructor method
        super(WelcomeScreen, self).__init__(**kwargs)
        welcomePage = FloatLayout()
        box = BoxLayout(orientation='vertical', size_hint=(0.4, 0.3),
                                       padding=8, pos_hint={'top': 0.5, 'center_x': 0.5})
        self.cameraObject = Camera(play=False)  ## WANT TO USE THIS VARIABLE IN OTHER CLASS
        self.cameraObject.play = True
        self.cameraObject.resolution = (700, 400)
        self.add_widget(self.cameraObject)

class FunctionScreen(Screen):  
    def __init__(self, **kwargs): 
        super(FunctionScreen, self).__init__(**kwargs) #init parent

        functionPage = FloatLayout()
        functionLabel = Label(text='what functions to use',
                          halign='center', valign='center', size_hint=(0.4,0.2), pos_hint={'top': 1, 'center_x': 0.5})
        self.img = self.cameraObject ## HERE I WANT TO USE 'self.cameraObject' VARIABLE

How to get "self.cameraObject" from class WelcomeScreen(Screen) to class FunctionScreen(Screen)? Thanks in advance :)

Upvotes: 0

Views: 93

Answers (2)

Codesidian
Codesidian

Reputation: 310

You need to take your cameraObject instance out of your classes and pass the single instance of cameraObject to them:

    cameraObject = Camera(play=False)  
    cameraObject.play = True
    cameraObject.resolution = (700, 400)
    WelcomeScreen(foo,bar,cameraObject)
    FunctionScreen(foo,bar,cameraObject)

It's that or create the camera outside of your classes:

cameraObject = Camera(play=False)  
cameraObject.play = True
cameraObject.resolution = (700, 400)

class WelcomeScreen(Screen): #welcomeScreen subclass
    def __init__(self, **kwargs): #constructor method
        super(WelcomeScreen, self).__init__(**kwargs)
            ...
        self.add_widget(cameraObject)

class FunctionScreen(Screen):  
    def __init__(self, **kwargs): 
        super(FunctionScreen, self).__init__(**kwargs) #init parent
            ...
        img = cameraObject 

I also think this might be helpful on the same camera for multiple screens in kivy.

Upvotes: 0

Roberto Trani
Roberto Trani

Reputation: 1227

I think that your cameraObject should belong to the Screen class or some intermediate abstraction, as it is used by both sub-classes. In this way, the superclass instantiates the cameraObject and any subclass can use it.

Upvotes: 1

Related Questions