Should I Use DAO Objects In Python __init__? - python

In python, which is better:
class MyAPI:
def __init__(self):
self.dao = MyDAO()
def getsomething(self):
something = self.dao.grabSomething()
newsomething = operateon(something)
return newsomething
def getsomethingelse()
somethingelse = self.dao.grabSomethingElse()
newsomethingelse = operateon(somethingelse)
return newsomethingelse
OR
class MyAPI:
def getsomething(self):
dao = MyDAO()
something = dao.grabSomething()
newsomething = operateon(something)
return newsomething
def getsomethingelse()
dao = MyDAO()
somethingelse = dao.grabSomethingElse()
newsomethingelse = operateon(somethingelse)
return newsomethingelse
I am a complete python noob coming from a java spring background and I am really trying to understand the difference here.

Related

how to create a python object from a json paylaod, without declaring each variable manually

basically I've got a booking class with fields each declared manually. I am curious if theres a more neat solution for the given task.
class Booking:
def __init__(self, json_data):
self.referenceNumber = json_data["referenceNumber"]
self.fromDate = json_data["fromDate"]
self.preferredDate1 = json_data["preferredDate1"]
self.preferredTimeFrom = json_data["preferredTimeFrom"]
self.time = json_data["time"]
self.partySize = json_data["partySize"]
self.budgetAmountTotal = json_data["budgetAmountTotal"]
self.budgetAmountPerPerson = json_data["budgetAmountPerPerson"]
self.budgetCurrencySign = json_data["budgetCurrencySign"]
self.venueName = json_data["venueName"]
self.venueId = json_data["venueId"]
self.cityName = json_data["cityName"]
self.clientName = json_data["clientName"]
self.clientContactName = json_data["clientContactName"]
self.status = json_data["status"]
self.statusText = json_data["statusText"]
self.assigneeId = json_data["assigneeId"]
self.assignee = json_data["assignee"]
self.lastAction = json_data["lastAction"]
self.inquiryChannel = json_data["inquiryChannel"]
self.venueDateFormat = json_data["venueDateFormat"]
self.bookingId = json_data["bookingId"]
self.inquiryHold = json_data["inquiryHold"]
self.isSpaceSelectedForHolds = json_data["isSpaceSelectedForHolds"]
self.id = json_data["id"]
bonus if i am not given an unresolved reference warning when I am calling for the attribute.
A simple self.__dict__.update(json_data) might do the trick.
Given the code in the question, access to attributes would be, for example, in the style of:
Booking().fromDate
However, if you don't mind accessing the value by its key name then you can greatly simplify the code as follows:
class Booking:
def __init__(self, json_data):
self._json = json.data
def __getitem__(self, key):
return self._json.get(key)
Then (for example)...
pd = {'fromDate': '2022/10/18'}
print(Booking(pd)['fromDate'])
How about this?
def set_attr_from_json(obj, json_data):
for key, value in json_data.items():
setattr(obj, key, value)
class Booking:
def __init__(self, json_data):
set_attr_from_json(self, json_data)
Since you want to control how your class attributes should be built, I think you should use metaclass like this
import json
from types import SimpleNamespace
class BookingMeta(type):
def __call__(self, json_data):
obj = super().__call__(json_data)
obj = json.loads(json.dumps(json_data), object_hook=lambda d: SimpleNamespace(**d))
return obj
class Booking(metaclass=BookingMeta):
def __init__(self, json_data):
pass
b = Booking({"name": {"first_name": "hello", "last_name": "world"}, "age": 23, "sub": ["maths", "Science"]})
print(b.name.first_name)
print(b.age)
#hello
#23

Initiate property inside python class

I'm trying to initiate a property inside a class but it doesn't seem to work.
The class should use another class. this is the code I've made:
Book.py:
from Paragraph import Paragraph as Paragraph
'''definitions'''
class Book:
def __init__(self, book):
self._paragraphs = book
'''paragraphs property'''
#property
def paragraphs(self):
return self._paragraphs
#paragraphs.setter
def paragraphs(self, book):
paragraph_0 = Paragraph(book[0x0:0x100])
paragraph_1 = Paragraph(book[0x200:0x300])
paragraph_2 = Paragraph(book[0x300:0x400])
paragraph_3 = Paragraph(book[0x400:0x500])
self._paragraphs = [paragraph_0, paragraph_1, paragraph_2, paragraph_3]
Paragraph.py:
'''definitions'''
class Paragraph:
def __init__(self, paragraph):
self._paragraph = paragraph
self._first_section = paragraph[0x0:0x10]
self._second_section = paragraph[0x10:0x100]
'''paragraph property'''
#property
def paragraph(self):
return self._paragraph
#paragraph.setter
def paragraph(self, paragraph):
self._paragraph = paragraph
'''first_section property'''
#property
def first_section(self):
return self._first_section
#first_section.setter
def first_section(self, first_section):
self._first_section = first_section
'''second_section property'''
#property
def second_section(self):
return self._second_section
#second_section.setter
def second_section(self, second_section):
self._second_section = second_section
Then I create a Book instance:
first_book = Book(some_hex_list)
And I expect to have 4 paragraphs in first_book._paragraphs and each paragraph should have a first and a second section property (as in the Paragraph class). Instead first_book._paragraphs just contains the original some_hex_list data.
I'd like to create a Book instance and initiate it so in the end I should get something like this:
first_book
-->_paragraphs
----->paragraph_0
---------->_first_section
---------->_second_section
----->paragraph_1
---------->_first_section
---------->_second_section
----->paragraph_2
---------->_first_section
---------->_second_section
----->paragraph_3
---------->_first_section
---------->_second_section
Thanks!

Python class recording attributes without specifying self ?

I have a question regarding a Python class I use in Blender. Basically, I wonder how the class works because some attributes are recorded without me specifically writing self.value = something. Here's the code:
class DialogOperator(bpy.types.Operator):
bl_idname = "object.dialog_operator"
bl_label = "Save/Load animation"
saving = bpy.props.BoolProperty(name="Save ? Else load.")
path_to_anim = bpy.props.StringProperty(name="Path to folder")
anim_name = bpy.props.StringProperty(name="Animation name:")
# path_to_anim += "/home/mehdi/Blender/Scripts/"
def execute(self, context):
# print('This is execute with: Saving: {} Name:{}'.format(self.saving, self.path_to_anim))
if self.saving:
self.launch_save()
message = 'Animation {} saved at {}'.format(self.anim_name, self.path_to_anim)
else:
self.launch_load()
message = 'Animation {} loaded'.format(self.anim_name)
self.report({'INFO'}, message)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def launch_load(self):
full_path = self.path_to_anim + self.anim_name
target_armature = Humanoid(bpy.data.objects['Armature'])
load_all(full_path, target_armature, 'LastLoaded')
def launch_save(self):
full_path = self.path_to_anim + self.anim_name
source_armature = Humanoid(bpy.data.objects['Armature'])
curves = source_armature.get_curves()
save_all(curves, source_armature,full_path)
Now, how come saving, path_to_anim and anim_name are considered as attributes (I'm able to call them in execute() and launch()) even though I did not write self.saving = saving
Thanks !
This is because saving,path_to_anim and anim_name are class attributes. They are defined for the class and not for a particular instance. They are shared among the instances. Here is a link for further explanation class-instance-attributes-python

Passing Data Between Classes in Python

I am attempting a practice task I found in an old programming book to increase my knowledge of classes in Python. The task is to create a program which allows a user to set up a series of tests for a school. Each test must contain no more than 10 questions. The task stated that the best way to do this was to use containment, and have the class 'Question' inside the class 'Test'
Basically, I should set up a class called Test which dewfines the basics of the whole test, and then a class called Quesion which sets up the question and passes it back to Test to be included in the array there. I'm having 2 major problems. Firstly, how do I get the setQuestion object in the Question class to pass data in to the Question array in the Test class. Secondly, how do I have the setQuestion object iterate the variable numberofQuestions since that's contained in the Test Class.
Here is the code. Not sure it's clear from the formatting but the Question class is inside the Test class:
class Test(object):
def __init__(self):
self.__testID = 0
self.__maxMarks = 0
self.__questions = []
self.__numberofQuestions = 0
self.__level = ""
self.__dateSet = ""
class Question(object):
def __init__(self):
self.__questionID = 0
self.__questionText = ""
self.__answer = ""
self.__marks = 0
self.__topic = ""
def setQuestion(self, questionID, questionText, answer, marks, topic):
self.__numberofQuestions = self.__numberofQuestions + 1
self.__questionID = self.__questionID
self.__questionText = self.__questionText
self.__answer = self.__answer
self.__marks = self.__marks
self.__topic = self.__topic
This is how I would do that:
class Test(object):
def __init__(self,id,marks):
self.__testID = id
self.__maxMarks = marks
self.__questions = []
self.__numberofQuestions = 0
self.__level = ""
self.__dateSet = ""
def setQuestion(self,question):
self.__numberofQuestions += 1
self.__questions.append(question)
class Question(object):
def __init__(self,id,text,answer,marks,topic):
self.__questionID = id
self.__questionText = text
self.__answer = answer
self.__marks = marks
self.__topic = topic
Now you can put question objects into the __question array of Test like that:
if __name__ == "__main__":
test = Test(1,100)
test.setQuestion(Question(1,"Text","Answer",50,"Topic"))

Python class wont add to objectStore

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)

Categories