Use other class functions in another class without creating a new instance - python

I am trying to develop a robot for Skype and I am having difficulties with certain classes and how to use only one instance instead of creating a new one within another file.
I have many files in which the robot runs from and I want to only use one instance via a Global.py file:
from classes import class_Core
from classes import class_Skype
from classes import class_Message
from classes import class_Commands
global Core, Skype, Message, Commands
Core = class_Core.Core()
Skype = class_Skype.Skype()
Message = class_Message.Message()
Commands = class_Commands.Commands()
I also have a Skypebot.py file which imports the Global.py file:
import Global
However, when I run Skypebot.py and use a function from Core in the Skype class:
class Skype:
def __init__(self):
Core.Log("Initialising Skype!")
I get an trace back:
Traceback (most recent call last):
File "C:\Users\Connor\Desktop\Skypebot 0.4\Skypebot.py", line 1, in <module>
import Global
File "C:\Users\Connor\Desktop\Skypebot 0.4\Global.py", line 9, in <module>
Skype = class_Skype.Skype()
File "C:\Users\Connor\Desktop\Skypebot 0.4\classes\class_Skype.py", line 8, in
__init__
Core.Log("Initialising Skype!")
NameError: global name 'Core' is not defined
Can anybody help me on this? Thanks!

You want this in skypebot.py, instead of import Global:
from Global import Core
You also don't need the global Core, Skype, Message, Commands line, since those variables are already being declared at a global scope within Global.py, as doukremt mentioned. The "global" keyword would be used if you then wanted to access/modify a global variable instance a function or method, e.g.
var = 3
def some_func():
var = 2 # This creates a locally-scoped variable named var, and assigns it to 2.
def some_other_func():
global var
var = 2 # This sets the globally-scoped variable var to 2.

Related

How to use built-in modules in a function of a string using exec()

I am running a websocket python file. In that,I created built-in modules in a function using imp module and I am executing a function of string using exec() in another function.
I use those built-in modules as globals parameter in exec().
But when I use those modules in the function of string, it throws following error
'module' object has no attribute 'pose'
However,using those modules outside the function of string works perfectly and returns expected values. But how to use inside the function?.
Here is the full code
import imp
import sys
import time
def generate_modules():
destination_module = imp.new_module("destination")
destination_module.destination = imp.new_module("destination")
destination_module.destination.pose = "Hello World"
# Define GUI module
gui_module = imp.new_module("GUI")
gui_module.GUI = imp.new_module("GUI")
gui_module.GUI.robotPose = lambda: "robotPose"
sys.modules["destination"] = destination_module
sys.modules["GUI"] = gui_module
return gui_module,destination_module
#Main function
def process_code():
gui_module,destination_module = generate_modules()
builtin_modules = {"GUI": gui_module,"destination":destination_module,"time": time}
globl = globals()
global_functions = globl.copy()
global_functions.update(builtin_modules)
sequential_code = """from GUI import GUI
from destination import destination
def generatepath():
data = destination.pose
pose = GUI.robotPose()
return data"""
dic = {}
exec(sequential_code,global_functions,dic)
func = dic["generatepath"]
value = func()
return value
process_code()
Thank you, any help is appreciated
As per the exec documentation:
If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
Notably, members of a class scope are not visible inside any nested scope. The alias resulting from from destination import destination is only visible in the top scope, not inside the function.
A simple solution is to omit the locals dictionary:
...
exec(sequential_code,global_functions)
func = global_functions["generatepath"]
...

Python - Calling a definition inside a class within another file

I am currently working on the framework for a simple turn based game. I am trying to call a definition within a class Inside of a separate file from my current one. The Program I am importing the moveset file from is called Pymon_Movesets. I am importing it into the Pymon_Main file. The code for both looks a little like this...
(Pymon_Moveset)
class normaltype():
def scratch():
type = normal
slot = 1
# Base normal type move
damage = 2 * level/2
Pymon_Main
From Pymon_Movesets import *
def Initialize():
Scratch = Pymon_Movesets.normaltype.scratch()
Bite = Pymon_Movesets.normaltype.bite()
My Error
File "C:\Users\samsc\Desktop\Pymon\Pymon_main.py", line 2, in <module>
from Pymon_Movesets import * File "C:\Users\samsc\Desktop\Pymon\Pymon_Movesets.py", line 3, in <module>
import Pymon_main File "C:\Users\samsc\Desktop\Pymon\Pymon_main.py", line 110, in <module>
gamefunction.Initialize() File "C:\Users\samsc\Desktop\Pymon\Pymon_main.py", line 26, in Initialize
Scratch = Pymon_Movesets.normaltype.scratch() AttributeError: module 'Pymon_Movesets' has no attribute 'normaltype' The program
'[4908] python.exe' has exited with code -1073741510 (0xc000013a).
I am Using Visual Studios Python Editor.
Thank you for your time
You are importing all the contents of Pymon_Moveset.py into the current namespace, however, you still call the class using the filename. Also, you need to create an instance of the class before you call a method. Lastly, you need to include self in the method signature, so it is bound to the class:
In Pymon_Movesets:
class normaltype():
def scratch(self):
type = normal
slot = 1
# Base normal type move
damage = 2 * level/2
In main file:
import Pymon_Movesets
def Initialize():
Scratch = Pymon_Movesets.normaltype().scratch()
Bite = Pymon_Movesets.normaltype().bite()
However, if you want to access the methods in the class using the name of the class and not an instance, use staticmethod:
In Pymon_Moveset.py:
class normaltype():
#staticmethod
def scratch():
type = normal
slot = 1
# Base normal type move
damage = 2 * level/2
Since you're doing from Pymon_Movesets import *, no need to use Pymon_Movesets to call its normaltype function if it is a module-level / file-level function.
from Pymon_Movesets import *
def Initialize():
Scratch = normaltype.scratch()
Bite = normaltype.bite()

Using object defined in other file without importing

I want to refer to an object in the namespace of the file that imports the one that I am writing.
this is an example:
main.py
from imp import * # main is importing the file I'm writing
...more code...
obj=1 # main defines obj
f() # f(), defined in imp, needs to use obj
...more code using obj...
This is the file that defines f():
imp.py
def f():
return obj # I want to refer to main's obj here
error on runtime:
error: global name 'obj' is not defined
How can it be done?
Thanks.
Relying on global variables across modules is not really a good idea. You should pass obj as a parameter to the function f(), like this:
f(obj)
Then just declare the parameter in the function:
def f(obj):
# code to operate on obj
return obj

Python globals var different inside class when imported

This is clearly a scope or import issue of some kind, but I can't figure it out. Something like:
classes.py
class Thing(object):
#property
def global_test(self):
return the_global
And then...
test.py
from classes import Thing
global the_global
the_global = 'foobar'
t = Thing()
t.global_test
:(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "classes.py", line 4, in global_test
return the_global
NameError: global name 'the_global' is not defined
Any help would be great!
"global" in Python is a variable accessible in top level within module.
This message:
NameError: global name 'the_global' is not defined
raised within classes.py means you do not have a global named the_global within your classes.py file.
Python modules do not share global variables. (well, not in the way you want them to share)
The 'global' variables only defines a variable as global inside the scope of the module
where it is used. You can not use 'global' here to access a variable outside the module
scope of the 'classes' module.
The proper solution here if you have to deal with global defines or so: move the "global"
variables into a dedicated module and use a proper import statement to import the variables
into your 'classes' module.
myvars.py:
MY_GLOBAL_VAR = 42
classes.py:
import myvars
class Thing():
def method(self):
return myvars.MY_GLOBAL_VAR # if you need such a weird pattern for whatever reason

Why am I unable to perform a simple operation in the __init__ of my class?

Given below is a snippet from a class of which I am trying to create objects and getting error:
class FoF(object):
def __init__(self,path):
filepath=[]
filepath.append(self.FileOrFolder(path))
Upon executing which I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
def __init__(self,path):
NameError: global name 'filepath' is not defined
After which I tried:
filepath=[]
class FoF(object):
def __init__(self,path):
global filepath.append(self.FileOrFolder(path))
And again:
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
global filepath.append(self.FileOrFolder(path))
NameError: global name 'filepath' is not defined
What is causing the error and how do I fix it?
Try using insted of global the special word self.
So something like this
class FoF(object):
def __init__(self,path):
self.filepath=[]
self.filepath.append(self.FileOrFolder(path))
The reason this error comes up is because what python thinks you're trying to do is one of two things:
Either you're trying to reference a global variable called filepath -- which is clear that's not what you're trying
What's not so clear is that you could also define a class attribute called filepath -- the only problem with that is that you can't define a class attribute with a function of that class. You can only do so within the class -- outside a class function
So in order to declare variables within a function you have to use the word self before it.
Edit** if you want it to be an attribute of the class -- as I'm assuming is what you meant you could do so like this:
class FoF(object):
filepath=[]
def __init__(self,path):
self.filepath.append(self.FileOrFolder(path))
I don't think you're giving us enough information. For example:
>>> class FoF(object):
... def __init__(self, path):
... junk = []
... junk.append(path)
...
>>> foo = FoF('bar/path')
produces no error.
What, exactly, are you trying to do?

Categories