so i need to use a dictionary within another file but am getting an error when importing the file. my file is called "Final Chess Game.py" with the spaces.
here is how im calling it:
from Final Chess Game import pieces
"pieces" is my dict.
Im getting an error on "Chess" within the import, do i have to change the name of the file or is there any other way of calling the dictionary from the final chess game file?
It is simply bad practice to have spaces in your import. Python thinks that you are trying to import Final and reads a syntax error when you get to Chess. You should rename your file to something without spaces.
If you absolutely want to import that file:
Final_Chess_Game = __import__("Final Chess Game")
Now you can call functions from Final Chess Game through Final_Chess_Game.<functioname>
If your chessboard class looks like this:
class ChessBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=70, color1="White", color2="lightgrey"):
self.rows = rows
self.columns = columns
self.size = size
self.color1 = color1
self.color2 = color2
self.pieces = {}
You cannot import a class variable without importing the whole class. You must import the whole chessboard. You can access the chessboard with:
Final_Chess_Game.ChessBoard
You cannot self.pieces without first creating an instance of the class. self.pieces is an instance variable, so each ChessBoard that you create has a .pieces variable.
Related
I am attempting to sort a dataframe by a column called 'GameId', which are currently of type string and when I attempt to sort the result is unexpected. I have tried the following but still return a type string.
TEST['GameId'] = TEST['GameId'].astype(int)
type('GameId')
One way to make the data life easier is using dataclasses!
from dataclasses import dataclass
# here will will be calling the dataclass decorator to send hints for data type!
#dataclass
class Columns:
channel_id : int
frequency_hz : int
power_dBmV : float
name : str
# this class will call the data class to organise the data as data.frequency data.power_dBmV etc
class RadioChannel:
radio_values = ['channel_id', 'frequency', 'power_dBmV']
def __init__(self, data): # self is 'this' but for python, it just means that you mean to reference 'this' or self instance
self.data = data # this instances data is called data here
data = Columns(channel_id=data[0], frequency=data[1], power_dBmv=data[4], name=data[3]) # now we give data var a val!
def present_data(self):
# this is optional class method btw
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(title="My Radio Channels")
for item in self.radio_values:
table.add_column(item)
table.add_row(data.channel_id, data.frequency_hz, data.power_dBmv)
console.print(table)
# ignore this if its confusing
# now inside your functional part of your script
if __name__ == '__main__':
myData = []
# calling an imaginary file here to read
with open("my_radio_data_file", 'r') as myfile:
mylines = myfile.readlines()
for line in myline:
myData.append(line)
myfile.close()
#my data would look like a string ["value", value, 00, 0.0, "hello joe, from: world"]
ch1 = radioChannel(data=myData[0])
ch1.present_data()
This way you can just call the class object on each line of a data file. and print it to see if it lines up. once you get the hang of it, it starts to get fun.
I used rich console here, but it works well with pandas and normal dataframes!
dataclasses help the interpreter find its way with type hints and class structure.
Good Luck and have fun!
Currently I am extracting files to the temp directory of the operating system. One of the files is a Python file containing a class which I need to get a handle of. The Python's file is known, but the name of the class inside the file is unknown. But it is safe to assume, that the there is only one single class, and that the class is a subclass of another.
I tried to work with importlib, but I am not able to get a handle of the class.
So far I tried:
# Assume
# module_name contains the name of the class and -> "MyClass"
# path_module contains the path to the python file -> "../Module.py"
spec = spec_from_file_location(module_name, path_module)
module = module_from_spec(spec)
for pair in inspect.getmembers(module):
print(f"{pair[1]} is class: {inspect.isclass(pair[1])}")
When I iterate over the members of the module, none of them get printed as a class.
My class in this case is called BasicModel and the Output on the console looks like this:
BasicModel is class: False
What is the correct approach to this?
Edit:
As the content of the file was requested, here you go:
class BasicModel(Sequential):
def __init__(self, class_count: int, input_shape: tuple):
Sequential.__init__(self)
self.add(Input(shape=input_shape))
self.add(Flatten())
self.add(Dense(128, activation=nn.relu))
self.add(Dense(128, activation=nn.relu))
self.add(Dense(class_count, activation=nn.softmax))
Use dir() to get the attributes of the file and inspect to check if the attribute is a class. If so, you can create an object.
Assuming that your file's path is /tmp/mysterious you can do this:
import importlib
import inspect
from pathlib import Path
import sys
path_pyfile = Path('/tmp/mysterious.py')
sys.path.append(str(path_pyfile.parent))
mysterious = importlib.import_module(path_pyfile.stem)
for name_local in dir(mysterious):
if inspect.isclass(getattr(mysterious, name_local)):
print(f'{name_local} is a class')
MysteriousClass = getattr(mysterious, name_local)
mysterious_object = MysteriousClass()
so I am writing code where I generate certain data in a class and save it in a dictionary. I want to use that data in the second class . The first class is as fellows:
class DataAnalysis():
def __init__(self,matfile=None):
'''Constructor
'''
self.matfile= matfile
def get_alldata(self):
print('all dict data accessed')
print(bodedata_dict)
return bodedata_dict
if __name__ == '__main__':
obj1= DataAnalysis(matfile=matfile)
"do some work"
bodedata_dict.update(bode_data)
obj1.get_alldata()
I then access the dictionary in the second class as:
from A import DataAnalysis
class PlotComaparison(DataAnalysis):
if __name__ == '__main__':
obj= DataAnalysis(matfile=None)
obj1= PlotComaparison(obj)
dict_data= obj.get_alldata()
But when I run the script with the second class, it gives me the following error:
File "DataAnalysis.py", line 301, in get_alldata
print(bodedata_dict)
NameError: name 'bodedata_dict' is not defined
I am very new to the concept of classes in python, so please help me with how I can use data from one class into another.
The get_alldata() method in the DataAnalysis class you defined is returning a bodedata_dict which isn't defined anywhere. It's like printing the content of a variable without defining it first.
EDIT:
Looking further into it, bodedata_dictin the first example comes from outside the class. You would likely want to change the flow of your program so that when DataAnalysis has it's get data method called, it doesn't depend on an outside state.
I have model
Order(models.Model):
name = models.Charfield()
#classmethod
do_something(cls):
print('do soemthing')
What I want to do is to move do_something method from my model to another file.I want to do it because I have several other big methods in this model and want to structure the code, don't like lengh of this file. It's getting big > 700 lines of code.
So I want to move my method to another file and import it, so it still can be used like modelmethod
like this:
Order.do_something()
Any ideas?
Use inheritance -- (wiki)
# some_package/some_module.py
class MyFooKlass:
#classmethod
def do_something(cls):
# do something
return 'foo'
# my_app/models.py
from some_package.some_module import MyFooKlass
class Order(models.Model, MyFooKlass):
name = models.CharField()
I'm trying to make multiple classes that will use the same set of defintions that already exist in my code.
class FT_Ten(PrinterInterface):
name = "Big Foot"
QueryCmd = "M107"
ActionCmd = "M108"
def __init__(self, device="/dev/ttyACM0"):
self.device = device
def hexformat(self, string):
out = "".join("{:x}".format(ord(x)) for x in string)
return out
def _console_print(self, line):
sys.stdout.write(line)
Theres about 90 more lines of code for this class. I need to add three more classes that share these definitions. The only differences are in the first few lines. Name, QueryCmd, and ActionCmd.
Ive tried simply breaking the the code at the begining of the definitions but im only familiar using a single class at a time.
How can i add more classes and use all the definitions that followed the first?
I've looked here trying to figure this out..
Define methods for multiple classes