Help with variables "across" classes

Do you have questions about writing plugins or scripts in Python? Meet the coders here.
Post Reply
krambriw
Plugin Developer
Posts: 2570
Joined: Sat Jun 30, 2007 2:51 pm
Location: Stockholm, Sweden
Contact:

Help with variables "across" classes

Post by krambriw » Wed Mar 05, 2008 12:09 pm

Can you advice me what is best?

I have in the following example two classes, one eg.PluginClass and one object class. I want to set a variable value (myCounter) in the object class and be able to use it in the PluginClass. How would you write it in python "as professional" as possible? Without using global variables. Hope you understand...

Thanks in advance, Walter

Code: Select all

class Device(eg.PluginClass):

    def ReadCounter(self):
        value = myCounter        



class Counter(object):

    def Configure(self):
        myCounter = 5

User avatar
dexter98
Plugin Developer
Posts: 49
Joined: Sun Dec 30, 2007 2:45 am
Location: Netherlands
Contact:

Re: Help with variables "across" classes

Post by dexter98 » Thu Mar 06, 2008 5:28 pm

Where are the counter objects created?
If this is done within the plugin class, the variable can easily be accessed from the plugin class.

The best way to access such functionality is through wrapper member functions in the counter class, such as GetCounter. It's best practice not to access the variables from a certain class should directly from other classes (except derived classes).

In your case:

Code: Select all

class Device(eg.PluginClass):

    def __init__(self):
        self.counter = Counter()

    def ReadCounter(self):
        self.counter.Increase()
        value = self.counter.GetCount()


class Counter(object):

   def __init__(self):
      self.myCounter = 0

   def GetCount(self):
      return self.myCounter

   def Increase(self):
      self.myCounter += 1

   def Configure(self):
      self.myCounter = 5


krambriw
Plugin Developer
Posts: 2570
Joined: Sat Jun 30, 2007 2:51 pm
Location: Stockholm, Sweden
Contact:

Re: Help with variables "across" classes

Post by krambriw » Fri Mar 07, 2008 6:32 am

Dear Dexter, thanks a lot for your advice. I'm experimenting with this now...

Best regards, Walter

Post Reply