Class object not returning value - python

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)

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

Why are there two elements in the collection?

I have got the following python script:
import enum
class ContactDetail():
def __init__(self, name=None, telecom=[]):
self.name = name
self.telecom = telecom
class ContactPoint():
def __init__(self, system=None, value=None, use=None, rank=None, period_start=None, period_end=None):
self.system = system # ContactPointSystem
self.value = value
class ContactPointSystem(enum.Enum):
email = "email"
url = "url"
oneConDet = ContactDetail()
oneConDet.name = 'test01'
oneConPoi = ContactDetail.ContactPoint()
oneConPoi.value = "url01"
oneConPoi.system = ContactDetail.ContactPoint.ContactPointSystem.url
oneConDet.telecom.append(oneConPoi)
print(len(oneConDet.telecom))
oneConDet = ContactDetail()
oneConDet.name = 'test02'
oneConPoi = ContactDetail.ContactPoint()
oneConPoi.value = "url02"
oneConPoi.system = ContactDetail.ContactPoint.ContactPointSystem.url
oneConDet.telecom.append(oneConPoi)
print(len(oneConDet.telecom))
Now when executing the script the first print results in 1. However, the second print prints 2.
I would expect the second print to be 1. Where is my mistake?

Writing Base class using object oriented programming

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

Trying to use setter but i get a this error : #versionNum.setter AttributeError: 'int' object has no attribute 'setter'

class Mobile:
def __init__(self,versionNum, isAndroid, memorysize):
self.__versionNum = versionNum
self.__isAndroid = isAndroid
self.memorySize = memorysize
self.__appArray = []
self.used_memory = 0
#versionNum.setter
def versionNum(self, versionNum):
self.__versionNum = versionNum
#isAndroid.setter
def isAndroid(self, bool):
self.__isAndroid = bool
#memorysize.setter
def memorysize(self, size):
self.__memorysize = size
I use proprety setter to the version of Mobile but i get an error
There are several problems:
You can't have a setter without a getter
You probably want to avoid __ as a prefix (why)
self.memorySize is both an attribute and a property.
You probably want to avoid bool as a variable name as it shadows the built-in bool
PEP8 conventions say that attribute names should be camel-cased
See the below fixes.
class Mobile:
def __init__(self, version_num, is_android, memory_size):
self._version_num = version_num
self._is_android = is_android
self._memory_size = memory_size
self._app_array = []
self.used_memory = 0
#property
def version_num(self):
return self._version_num
#version_num.setter
def version_num(self, version_num):
self._version_num = version_num
#property
def is_android(self):
return self._is_android
#is_android.setter
def is_android(self, is_android):
self._is_android = is_android
#property
def memory_size(self):
return self._memory_size
#memory_size.setter
def memory_size(self, size):
self._memory_size = size

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