Python Forum
Global accessing of parameter to class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Global accessing of parameter to class (/thread-4524.html)



Global accessing of parameter to class - Mahamutha - Aug-23-2017

I need to access the variable from main.py to global_rrt.py. I need to access the variable serial_rrt_read in global_rrt.py under the calss frame_101.
global_rrt.py
global serial_rrt,serial_rrt_read           #Read data from RS232 port of fast charger
global serial_length                        #Determine the length of serial read from fast charger


from main import*
print serial_rrt_read
class frame_101:
        frame_101_serial =  "1111111100000000"
        frame_101_start  =  frame_101_serial[0:8]
        frame_101_f_id   =  frame_101_serial[8:16] 
        frame_101_end    =  frame_101_serial[632:640]

frame_101_data = frame_101()
#print frame_101_data.frame_101_serial
main.py
import time                     #Deals with date and time
#import serial                   #Acess for Serial Port
import subprocess               #Allows us to spawn processes
import os                       #Provides a way of using operating system dependent functionality
import sys                      #Access variables used or maintained by the interpreter
from global_rrt import*         #Access Global Variables in Main File

#Start Reading Serial Port Data
#serial_rrt = serial.Serial('/dev/ttyACM1', 9600, timeout=1)

while 1:
    #serial_rrt_read = ser.readline()
    serial_rrt_read = "1111111100000000"
    #print serial_rrt_read
    serial_length = len(serial_rrt_read)
    #print serial_length
    if(serial_length == 16):
        frame_101_data = frame_101()
        print "Hi"
        print frame_101_data.frame_101_serial
  
     



RE: Global accessing of parameter to class - Larz60+ - Aug-23-2017

You should take a tutorial on classes
see: https://docs.python.org/3/tutorial/classes.html


RE: Global accessing of parameter to class - ichabod801 - Aug-23-2017

There's also one on this forum, see the link in my signature.


RE: Global accessing of parameter to class - nilamo - Aug-23-2017

If you use the if __name__ == "__main__": check, you should be able to just import it.

# eggs.py

frame_data = 42

if __name__ == "__main__":
    import spam
    print(spam.other_data)
    print(frame_data) # what will this be?
# spam.py

import eggs
other_data = eggs.frame_data * 2
eggs.frame_data = 1
Output:
> python eggs.py 84 42
It's not a great way to do it, since each module would then have it's own concept of what the values are, so a change in one file won't be reflected in the other (as demonstrated).  It works for basic cases, but you're better off restructuring if you want something that works better.