Well. I have a main file with a class in it. I have another file, where i wanna store functions (for the sake of simplicity), which use functions of that class. And I wanna import the second file into the first one, so i can use those functions in main file. And that's where I encountered a problem.
If I'm just importing the second file into the first one, I have an error which says that in second file the class is not defined.
If I'm importing the first file into the second one AND the second one into the first one, I have an error in main file, which says that function I defined in second one doesn't exist.
That's the simpliest variant I can get. File 1:
import random
import Test2
class randoms():
def __init__(self):
pass
def random_shit():
a=random.randrange(19)
return a
WTF= randoms()
Test2.printer()
File 2:
import Test
def printer():
print(Test.WTF.random_shit())
First off some python customs: usually classes are defined with capital letters:
class Randoms():
pass
The problem is in file 2 and the fix will fix both errors for both files you define the object WTF in file 1 and then use it in a function. Basically you are using a variable which doesn’t exist inside the function. What you should do is initialize the object WTF inside the function you would like to use:
def printer():
WTF = Test.randoms()
print(WTF.random_shit())
You can remove the initialization inside the file 1.
Hope this helps.
Related
I'm making a small game and wanted a settings page function that's in a seperate .py file to keep things more clean and easily editable. I have a global variable called textSpeed (which I use the global keyword to use properly in the function) which I change in this runSettings function, but when I print the variable back in my main file it hasn't changed.
The code in the main file (main.py)
from settings import runSettings
textSpeed = "not set"
runSettings()
print(textSpeed)
The code from the settings fuction file (settings.py)
def runSettings():
global textSpeed
textSpeed = input("select text speed. ")
print(textSpeed)
return textSpeed
textSpeed is a local variable - local to the main module.
You need to reference the variable from settings.
import settings
settings.textSpeed = "not set"
runSettings()
print(settings.textSpeed)
To avoid circular import, I advise you to create a third file if you wish to keep it this way. Let's call it varSpeed.py with the following code:
global textSpeed
textSpeed = "not set"
Then you can import varSpeed from both other files have access to that variable without the circular issue.
The runSettings function already retuns the value it sets as well. Instead of messing with mixing namespaces and importing global variables, just use the returned value in main.py:
textSpeed = runSettings()
the problem is that you are trying to change a variable from a different file, while you have not imported the file. I think the easiest way to handle this is to use a class variable like this:
Main file:
from class_file import MyClass
MyClass.run_settings()
print(MyClass.text_speed)
Settings file:
class MyClass:
text_speed = 'n/a'
#staticmethod
def run_settings():
MyClass.text_speed = input("Select text speed: ")
return MyClass.text_speed
My friend asked me to build a function that can execute code in a for loop so, I was doing that and I was using exec in the same file I was declaring a variable name, now when I access name from exec, it says NameError: name 'name' is not defined
This thing is in multiple files, one that runs everything, second that includes all functions and one that calls all functions
I have tried to define variables inside exec and sure, it works.
I have tried Accessing variables in functions.py(File that contains every function) file and it works too.
I have tried merging functions.py and test.py(the file that's using exec) and then running it directly through python and it worked
My functions.py file
def forloop(current, maximum, code):
for x in range(current, maximum):
exec(str(code), globals())
My 'test.py'(It's the one where I call functions)
from functions import *
name = 'Ameer'
forloop(1,3,"""
echo(name)
""")
And, I am running it all through another exec in my 'runner.py'
from functions import *
file = open('test.py', "r+")
content = file.read()
exec(content)
Now, it's giving me an error saying NameError: name 'name' is not defined when it is defined. Please can you guys help me with this issue
You need to use the variables from the place where forloop is called.
import inspect
def forloop(current, maximum, code):
frame = inspect.currentframe().f_back
for x in range(current, maximum):
exec(str(code), frame.f_globals, frame.f_locals)
I am not too far into python yet and here is the case.
Say I have one python file called functions.py which holds a class with my functions. Below is an example.
import json
class Functionalities:
def addelement(element):
# code goes here`
And I have another python file, kind of 'executable' script which does all the job using functions from functions.py class
Adding from . import functions doesn't help.
How to I call functions from the class from another file?
Unlike java, you don't have to use classes in python. If a class is used only as a holder for functions, chances are that you want a free function (one without a class) instead.
But to answer your actual question, you can use the import statement. That will run the other .py file, and make the namespace available so you can call things defined there.
functions.py:
import json
class Functionalities:
def addelement(element):
# code goes here`
main.py:
import functions
f = functions.Functionalities()
f.addelement('some element')
In one file I create a class called Robot, but when I try to create an object of that class in another file it says:'module' object has no attribute 'Robot'
main.py
import robot as rob
robot=rob.Robot()
robot.py
class Robot(object):
def __init__(self):
return 0
def otherFunctions():
return 0
And it says: 'module' object has no attribute 'Robot'.
Where I am making a mistake?
The way your code is written is correct (barring removal you've presumably made for conciseness)
When you import, Python checks sys.path for importing locations, and imports the first robot it can find.
A couple ways to solve this:
import robot
print robot.__file__
in robot.py
print("hello!")
import sys
sys.path.insert('/path/to/correct/robot/')
import robot
It seems like the syntax in your robot.py file is not correct. You can correct the errors in the most direct way by changing your robot.py file to look like this:
class Robot(object):
def __init__(self):
pass
def other_functions(self):
pass
Note that I used snake casing for the other_functions function. Don't use camelCasing in Python. It's not idiomatic. Also, I added a self argument to other_functions so you won't get a TypeError if you try to invoke it off of a Robot instance.
Also, unless your code is truly as simple as you present it, the error might be coming from a circular import. Make sure you're not trying to import the two modules from each other before they've had a chance to fully execute.
Here is the start of my program. I want a lot of the functions to be inside the for loop as seen in the 3rd function here. How do I go about this?
#!/usr/bin/env python
from rdflib import URIRef, Graph
from StringIO import StringIO
import subprocess as sub
class Wordnet():
def __init__(self, graph):
graph = Graph()
def process_file(self, file):
file = open("new_2.txt", "r")
return file
def line_for_loop(self, file):
for line in file:
def split_pointer_part(self, before_at, after_at, line):
before_at, after_at = line.split('#', 1)
return before_at, after_at
def split_word_part(self, word_part, line):
word_part = line.split()
return word_part
Is it just a matter of indenting everything else in the for loop or is it when the function are called that the loop has to be defined?
How does one go about calling multiple functions as part of a program? I am new to python and i don't really know.
There's no program here. Classes by themselves don't do anything. You need to instantiate the class, then call one of its methods (which is the correct term for what you seem to be calling "processes"). So, at the end of this file, you might do:
wordnet = Wordnet()
my_file = wordnet.process_file()
wordnet.line_for_loop(my_file)
Inside one method, you can call another: so for your loop, you would do:
def line_for_loop(self, file):
for line in file:
self.my_method_1()
self.my_method_2()
There are some other issues with your code. For example, in the __init__ method, you define a graph local variable, but never do anything with it, so it is not stored anywhere. You need to store variables on self for them to become instance properties:
def __init__(self):
self.graph = Graph()
Also, you seem to be confused about when to pass parameters to functions. Twice (in __init__ and process_file) you accept a parameter, then override it inside the method with a local variable. If you're defining the variable in the function, you shouldn't pass it as a parameter.
Note that, as I've had occasion to say before, Python is not Java, and doesn't always require classes. In this case, the class is not contributing anything to the program, other than as a holder for methods. In Python, you would normally just use functions inside a module for that.
Process isn't the proper term to use. Those are better known as functions or methods. As far as Python loops go, indentation is important. You do need to indent.
def line_for_loop(self, file):
for line in file:
process_file("example_file_name.txt")
split_pointer_part(0, 10, "some test string")
You should make the function calls from inside the loop. The example code above may not be the exact solution for you code, but it should be sufficient enough to answer your question.