Link for my initial part of this question
I am new to object-oriented programming I need to write a BankDataWriterBase base class in the following program using the class diagram given in below to the code. I cannot understand the complete thing that the class diagram has, anybody here to know & explain to me what they actually saying using the class diagram
After my understanding I have done like this :
I know my approach is wrong but i don't know where the mistake happening
import pandas as pd
class ExcelParser:
def __init__(self):
self.config = []
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None, na_values= None, keep_default_na=False)
return [x for k, v in raw_excel.items() for x in v[v.columns.intersection(conf)].to_dict(orient='records')]
class BankDataWriterBase:
def __init__(self):
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name):
res = True
return res
if __name__ == "__main__":
conf = list(input("ENTER THE LIST HERE : ").split(','))
file_name = input("Enter the full input path here : ")
out_path = input("Enter the full path for the output : ")
bank_id = input("Enter the Bank ID : ")
obj = ExcelParser()
obj.config = conf
print(obj.extract(file_name))
obj1 = BankDataWriterBase()
obj1.output_path = out_path
obj1.bank_identifier = bank_id
print(obj1.write_file(file_name))
After seeing some of the answers i changed my code like the following
import pandas as pd
class ExcelParser:
def __init__(self):
self.config = []
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None, na_values= None, keep_default_na=False)
return [x for k, v in raw_excel.items() for x in v[v.columns.intersection(conf)].to_dict(orient='records')]
class BankDataWriterBase:
def __init__(self,file_name,out_path,bank_id):
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name:str):
res = True
return res
class BankDataWriterImpl(BankDataWriterBase):
def __init__(self, file_name, out_path, bank_id):
super().__init__(file_name, out_path, bank_id)
def extrac_json(self, file_name):
pass
if __name__ == "__main__":
conf = list(input("ENTER THE LIST HERE : ").split(','))
file_name = input("Enter the full input path here : ")
out_path = input("Enter the full path for the output : ")
bank_id = input("Enter the Bank ID : ")
obj = ExcelParser()
obj.config = conf
print(obj.extract(file_name))
obj1 = BankDataWriterBase()
obj1.output_path = out_path
obj1.bank_identifier = bank_id
print(obj1.write_file(file_name))
What they mean is that BankDataWriterImpl should inherit from BankDataWriterBase like so :
class BankDataWriterBase():
...
class BankDataWriterImpl(BankDataWriterBase):
# this class inherit from parent class BankDataWriterBase
# when a `BankDataWriterBase` object is created, parent.__init__ method is executed.
def extract_jon(self, filename: str):
pass
then in driver code, you can create a BankDataWriterImpl() object instead of the BankDataWriterBase() as you did.
It will inherit its __init__ method from parent and have a new extract_json method.
Another problem you didn't mention come from BankDataWriterBase attributes. Your code assume the existance of 3 global variables.
They should be passed to the class when you create the object, like so :
But watchout when creating a BankSomething object, since those arguments are now expected :
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
obj1 = BankDataWriterImpl(input_path, output_path, bank_identifier)
Edit after comment : but my lead said write class only for BankDataWriterBase()
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
def write_file(file_name: str):
pass
obj = BankDataWriterBase(input_path, output_path, bank_identifier)
# setattr add a new attribute to `obj`, first argument is the object,
# second argument its name (obj.name)
# third argument the attribute itself
# here we attach a new method `obj.write_file` to the object
setattr(obj, 'write_file', write_file)
# now you can use it like that :
# this line would have raised an exception before the `setattr` line
obj.write_file("correct_file_path")
the structure without implementations:
class Task:
def __init__(self): # initialise all the instance variables (None in this case)
pass # this this might need to be empty
def run(self) -> None:
pass
class BankDataWriterBase:
def __init__(self, file_name: str, out_path: str, bank_id: str):
# you might wan't to set default values: file_name: str = "" for example
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name) -> str:
pass
class BankDataWriterImpl(BankDataWriterBase):
# inherit from BankDataWriterBase, all functions and variables from BankDataWriterBase are now callable from this class
# as said in the other answer, this will be inherited so you don't need to have this
def __init__(self, file_name: str, out_path: str, bank_id: str):
super().__init__(file_name, out_path, bank_id) # call __init__ method of all the superclasses (in this case only BankDataWriterBase)
def extract_json(self, filename: str):
pass
Related
class Friend:
all = []
def __init__(self):
self.__fname = None
self.__lname = None
self.__fid = None
#property
def fname(self):
return self.__fname
#fname.setter
def fname(self, value):
self.__fname = value
#property
def lname(self):
return self.__lname
#lname.setter
def lname(self, value):
self.__lname = value
#property
def fid(self):
return self.__fid
#fid.setter
def fid(self, value):
self.__fid = value
#DB Class
class db_friend()
def db_load_friend(self, obj, fname,lname):
obj.fname = fname
obj.lname = lname
obj.fid = "XYZ"
obj.all.append(obj)
# function that acts on the friend class
def manage_friend():
fname = "Joe"
lname = "Root"
objfriend = Friend()
db_friend.db_load_friend(objfriend, fname,lname)
print (objfriend.fname) # this is not working
print (objfriend.fid) #this is not working
for user in objfriend.all:
print (objfriend.fid) #this is working
Both objfriend.fname and objfriend.fid is printing no value. I am trying to load the objfriend object by passing to the db_load_friend method of the db class. I am able to see the values if I loop through the "all" variable. May I know why this is not working or using the static variable "all" is the only way to do it?
You need to create an instance of db_friend so you can call the db_load_friend() method:
def manage_friend():
fname = "Joe"
lname = "Root"
objfriend = Friend()
objdbfriend = db_friend()
objdbfriend.db_load_friend(objfriend, fname,lname)
print (objfriend.fname)
print (objfriend.fid)
for user in objfriend.all:
print (objfriend.fid) #this is working
Or, since db_load_friend() doesn't need to use self, you could make it a static method.
class db_friend()
#staticmethod
def db_load_friend(obj, fname,lname):
obj.fname = fname
obj.lname = lname
obj.fid = "XYZ"
obj.all.append(obj)
No error when I start the script and but the callback of the class startSacnRec doesn't work and Visual Code give me the info "Callback is not accessed"
class sacnRec():
#contstruktur super().__init__(self) Elternklasse vererbung aufrufen
def __init__(self, fileName, universum):
self.fileName = fileName
self.universum = universum
def deleteFile(self):
with open(self.fileName + '.txt','w'): pass
def packettoIntData(data):
uniData = str(data)[1:-1]
uniDataList = [int(s) for s in uniData.split(',')]
return uniDataList
def writeCsv(set,data,fileName):
with open(fileName + '.txt', "a") as file:
file.write(str(set))
file.write(str(data))
def startSacnRec(self):
print("Start des Servers" + str(self.universum))
receiver = sacn.sACNreceiver()
receiver.start()
#receiver.listen_on('universe', universe=self.universum) # listens on universe 1
def callback(packet): # packet type: sacn.DataPacket
print(packet.dmxData)
print(packet.sourceName)
print("test")
#uniOneSet = [int(packet.universe),int(packet.priority),str(packet.sourceName) ]
#print(uniOneSet)
# uniOneDmx = packettoIntData(packet.dmxData)
#writeCsv(uniOneSet,uniOneDmx, name)
receiver.join_multicast(1)
time.sleep(10) # receive for 10 seconds
receiver.stop()
one = sacnRec(1,1)
one.startSacnRec()
I think the problem is here
enter image description here
Using a decorator (the #receiver.listen_on... part) is usually for class methods.
If you want to use a closure based callback, then use receiver.register_listener approach.
https://github.com/Hundemeier/sacn#receiving-1
I'm trying to load a spreadsheet and pass a list of the worksheets back to my QML interface. But I'm unable to find a way to provide a list(and later a dictionary) back to the QML script.
Here's my QML:
FileDialog {
id: openDialog
title: "Open spreadsheet"
nameFilters: [ "Excel files (*.xls *.xlsx)", "All files (*)" ]
selectedNameFilter: "Excel files (*.xls *.xlsx)"
onAccepted: {
file.load(fileUrl)
console.log(file.name)
console.log(file.sheetnames)
}
onRejected: {
console.log("Rejected")
}
}
Here's the my python class:
class File(QtCore.QObject):
def __init__(self, *args, **kwargs):
super(File, self).__init__(*args, **kwargs)
self.__filename = ""
self.__sheetnames = list()
#QtCore.Slot(str)
def load(self, filename):
self.__filename = re.sub(r'^[a-zA-Z]+:/+', '', filename)
# Load the worksheet using openpyxl.
try:
workbook = openpyxl.load_workbook(filename=self.__filename)
except openpyxl.utils.exceptions.InvalidFileException as exception:
# Todo: write code to pass error to the user.
print('Invalid File')
return
self.__sheetnames = workbook.sheetnames
print(workbook.sheetnames)
def set_filename(self):
return self.__filename
def get_filename(self, name):
self.__filename = name
def get_sheetnames(self):
return self.__sheetnames
def set_sheetnames(self, names):
self.__sheetnames = names
name = QtCore.Property(str, set_filename, get_filename)
sheetnames = QtCore.Property(list, get_sheetnames, set_sheetnames)
When I open a spreadsheet, the output is:
['Sheet1']
qml: C:/path/to/my/spreadsheet.xlsx
qml: QVariant(PySide::PyObjectWrapper)
The first line shows that python has the list correct, in the second my script in the QML is successfully getting a string property, but the third isn't getting the list property properly.
You have to use QVariantList instead of list, besides the use of regular expressions may fail, in my case I use Linux and I generate problems, so the correct thing to do is to use QUrl:
class File(QtCore.QObject):
filenameChanged = QtCore.Signal()
sheetnamesChanged = QtCore.Signal()
def __init__(self, *args, **kwargs):
super(File, self).__init__(*args, **kwargs)
self.__filename = ""
self.__sheetnames = list()
#QtCore.Slot(str)
def load(self, filename):
self.__filename = QtCore.QUrl(filename).toLocalFile()
# Load the worksheet using openpyxl.
try:
workbook = openpyxl.load_workbook(filename=self.__filename)
except openpyxl.utils.exceptions.InvalidFileException as exception:
# Todo: write code to pass error to the user.
print('Invalid File')
return
self.__sheetnames = workbook.sheetnames
print(workbook.sheetnames)
#QtCore.Property(str, notify=filenameChanged)
def filename(self):
return self.__filename
#filename.setter
def get_filename(self, name):
if name == self.__filename:
return
self.__filename = name
self.filenameChanged.emit()
#QtCore.Property('QVariantList', notify=sheetnamesChanged)
def sheetnames(self):
return self.__sheetnames
#sheetnames.setter
def set_sheetnames(self, names):
if names == self.__sheetnames:
return
self.__sheetnames = names[:]
self.sheetnamesChanged.emit()
Output:
['Periodic Table']
qml: /home/eyllanesc/Downloads/Ultimate Periodic Table1.xlsx
qml: [Periodic Table]
i have a code below
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer, MicrophoneRecognizer
djv = Dejavu(config)
Recognize audio from a file
song = djv.recognize(FileRecognizer, "mp3/Sean-Fournier--Falling-For-You.mp3")
below is from dejavu/recognize.py
class BaseRecognizer(object):
def __init__(self, dejavu):
self.dejavu = dejavu
self.Fs = fingerprint.DEFAULT_FS
def _recognize(self, *data):
matches = []
for d in data:
matches.extend(self.dejavu.find_matches(d, Fs=self.Fs))
return self.dejavu.align_matches(matches)
def recognize(self):
pass # base class does nothing
class FileRecognizer(BaseRecognizer):
def __init__(self, dejavu):
super(FileRecognizer, self).__init__(dejavu)
def recognize_file(self, filename):
frames, self.Fs, file_hash = decoder.read(filename, self.dejavu.limit)
t = time.time()
match = self._recognize(*frames)
t = time.time() - t
if match:
match['match_time'] = t
return match
def recognize(self, filename):
return self.recognize_file(filename)
I don't undersand how recognize takes class Filereognizer and also filename where recognizer is defined as
def recognize(self, filename):
and takes only filename as a parameter. can someone explain how this work and what it actually does???
thanks to #daniel here is my follow up question
def recognize(self, recognizer, *options, **kwoptions):
r = recognizer(self)
return r.recognize(*options, **kwoptions)
this is recognizer under Djavu class and I am thinking "self" from line "r = recognizer(self)" is what make recognizer(under Dejavu class) can receive FileRecognizer class as a parameter right?
this is from dejavu(audiofingerprint software) github and link is below :
https://github.com/worldveil/dejavu
for some reason when I try to add an object to a dictionary in a class, where the dictionary belongs to another class and objects are added/removed by class functions it always seems to fail adding.
Heres the datahandler :
class datastore():
def __init__(self, dict=None):
self.objectStore = {}
self.stringStore = {}
if dict is not None:
self.objectStore = dict
def __addobj__(self,obj,name):
print("adddedval")
self.objectStore[name] = obj
def __getobject__(self,name):
_data = self.objectStore.get(name)
return _data
def __ripobj__(self,name,append):
if isinstance(append, object):
self.objectStore[name] = append
def __returnstore__(self):
return self.objectStore
def __lst__(self):
return self.objectStore.items()
and heres the trigger code to try to add the item :
if self.cmd=="addtkinstance-dev":
print("Adding a tk.Tk() instance to dataStore")
#$$ below broken $$#
_get = datastore.__dict__["__returnstore__"](self.dat)
_get["test-obj"] = tk.Tk()
datastore.__init__(self.dat, dict=_get)
#--------------------------------------------#
tool(tk.Tk(), "test-obj", datastore())
and also heres the init for the class that trys to add the object
class cmdproc(tk.Tk, datastore):
def __init__(self,lst,variable_mem,restable):
self.pinst = stutils(lst,restable,variable_mem)
self.vinst = varutils(variable_mem,lst,restable)
self.tki = tkhandler()
self.dat = datastore(dict=None)
datastore.__init__(self, dict=datastore.__returnstore__(self.dat))
tk.Tk.__init__(self)
self.lst = lst
self.vdat = variable_mem
self.restable = restable
please help this is seriously baffling me
(note that tkhandler dosn't have to do with anything)