You are not logged in.

#1 2013-05-25 21:14:31

D-Player
Member
Registered: 2013-05-25
Posts: 1

[Python] Update GTK widget from a different class

#!/usr/bin/env python2

class One:
	
	def updateVariable(self):
		
		# Update variable of class 'Two'

class Two:
	
	variable = "DEFAULT VALUE"
	
	def __init__(self):
		
		one = One()
		
two = Two()

Is there any way I can update the variable from Two by calling a method in One?

This is just an example. The real life problem are two separate classes - GUI and gstreamer. I need to update some of GUI widgets from the gstreamer class, because bus messages should be parsed there and I can not move them outside of that class.

One more problem - I need class One to have an instance of class Two, but since Two comes after One, Python doesn't find it. What can be done with this?

Last edited by D-Player (2013-05-25 22:12:54)

Offline

#2 2013-05-25 22:17:46

Xyne
Forum Fellow
Registered: 2008-08-03
Posts: 6,965
Website

Re: [Python] Update GTK widget from a different class

"One" will need a reference to "Two". There are several ways to do it, e.g.

#!/usr/bin/env python2

class One:
	
	def updateVariable(self):
		
		# Update variable of class 'Two'
		self.two.variable = FOO

class Two:
	
	variable = "DEFAULT VALUE"
	
	def __init__(self):
		
		one = One()
		one.two = self
		
two = Two()

The better way to do this would likely to be restructure your code. You could, for example, create a subclass of "One" that accepts an instance of "Two" in its "__init__" method. For example:

class MyOne(One):
	__init__(self, two, *args, **kwargs):
		super(self.__class__, self).__init__(*args, **kwargs)
		# Or just use One.__init__(self, *args, **kwargs)
		# *args and **kwargs passes through arguments and keyword arguments to the parent class.
		self.two = two

	def updateVariable(self):
		self.two.variable = FOO

My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

Board footer

Powered by FluxBB