Class instances overwrite attributes - python

I've written a class in Python for calculations, it looks like:
default = {…}
class Case(object):
def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
self.name = name
self.burnup = burnup
self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
self.data = default
self.data['caseName'] = name
self.data['water-temp'] = str(wt)
self.data['water-den'] = str(wd)
self.data['fuel-temp'] = str(ft)
self.data['boron-con'] = str(bc)
self.cr_state = cr_state
self.data['cr_state'] = cr_state
self.data['burnup'] = str(burnup)
Actually it implements more methods, but this should be enough just to illustrate.
The problem is that when I'm trying to create different instances of this class they turn out to have same attributes, like:
basis = Case('basis', 578.0, 0.71614, 578.0, 0.00105, 0, 'empty')
wt450 = Case('wt450', 450.0, 0.71614, 578.0, 0.00105, 0, 'empty')
and after this if I check:
print basis.data == wt450.data
it returns True. Where can the root of the problem be?

Like the comment from jonrsharpe states, you could copy the content of the default dict with the `dict.copy method.
class Case(object):
def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
self.name = name
self.burnup = burnup
self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
# Copy the content of the dict
self.data = default.copy()
# Overwrite data's default values
self.data['caseName'] = name
self.data['water-temp'] = str(wt)
self.data['water-den'] = str(wd)
self.data['fuel-temp'] = str(ft)
self.data['boron-con'] = str(bc)
self.cr_state = cr_state
self.data['cr_state'] = cr_state
self.data['burnup'] = str(burnup)
Or, if you want to keep the values synchronized with the default ones, you could create a method that would take the value from the instance and if it can't find the value, then use the one on the default dict. It would look something like this:
class Case(object):
def __init__(self, name, wt, wd, ft, bc, burnup, cr_state):
self.name = name
self.burnup = burnup
self.infn = 'fa-'+faType+'-'+str(self.burnup)+'-'+self.name
# We create a NEW dictionary to hold the overwritten values
self.data = {}
# Write data to OUR OWN dict
self.data['caseName'] = name
self.data['water-temp'] = str(wt)
self.data['water-den'] = str(wd)
self.data['fuel-temp'] = str(ft)
self.data['boron-con'] = str(bc)
self.cr_state = cr_state
self.data['cr_state'] = cr_state
self.data['burnup'] = str(burnup)
def property(name):
"""
Return the value of `name`, if name wasn't defined, then use the
value from default.
"""
# Return the property from our own dict. If it can't find the property
# then get it from the default dict. If the property doesn't exists
# returns None.
return self.data.get(name, default.get(name))
# Then
print basis.property('caseName') == wt450.property('caseName')
> False

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

Class object not returning value

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)

Return class instance instead of creating a new one if already existing

I defined a class named Experiment for the results of some lab experiments I am conducting. The idea was to create a sort of database: if I add an experiment, this will be pickled to a db before at exit and reloaded (and added to the class registry) at startup.
My class definition is:
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Experiment(metaclass=IterRegistry):
_registry = []
counter = 0
def __init__(self, name, pathprotocol, protocol_struct, pathresult, wallA, wallB, wallC):
hashdat = fn.hashfile(pathresult)
hashpro = fn.hashfile(pathprotocol)
chk = fn.checkhash(hashdat)
if chk:
raise RuntimeError("The same experiment has already been added")
self._registry.append(self)
self.name = name
[...]
While fn.checkhash is a function that checks the hashes of the files containing the results:
def checkhash(hashdat):
for exp in cl.Experiment:
if exp.hashdat == hashdat:
return exp
return False
So that if I add a previously added experiment, this won't be overwritten.
Is it possible to somehow return the existing instance if already existant instead of raising an error? (I know in __init__ block it is not possible)
You can use __new__ if you want to customize the creation instead of just initializing in newly created object:
class Experiment(metaclass=IterRegistry):
_registry = []
counter = 0
def __new__(cls, name, pathprotocol, protocol_struct, pathresult, wallA, wallB, wallC):
hashdat = fn.hashfile(pathresult)
hashpro = fn.hashfile(pathprotocol)
chk = fn.checkhash(hashdat)
if chk: # already added, just return previous instance
return chk
self = object.__new__(cls) # create a new uninitialized instance
self._registry.append(self) # register and initialize it
self.name = name
[...]
return self # return the new registered instance
Try to do it this way (very simplified example):
class A:
registry = {}
def __init__(self, x):
self.x = x
#classmethod
def create_item(cls, x):
try:
return cls.registry[x]
except KeyError:
new_item = cls(x)
cls.registry[x] = new_item
return new_item
A.create_item(1)
A.create_item(2)
A.create_item(2) # doesn't add new item, but returns already existing one
After four years of the question, I got here and Serge Ballesta's answer helped me. I created this example with an easier syntax.
If base is None, it will always return the first object created.
class MyClass:
instances = []
def __new__(cls, base=None):
if len(MyClass.instances) == 0:
self = object.__new__(cls)
MyClass.instances.append(self)
if base is None:
return MyClass.instances[0]
else:
self = object.__new__(cls)
MyClass.instances.append(self)
# self.__init__(base)
return self
def __init__(self, base=None):
print("Received base = %s " % str(base))
print("Number of instances = %d" % len(self.instances))
self.base = base
R1 = MyClass("apple")
R2 = MyClass()
R3 = MyClass("banana")
R4 = MyClass()
R5 = MyClass("apple")
print(id(R1), R1.base)
print(id(R2), R2.base)
print(id(R3), R3.base)
print(id(R4), R4.base)
print(id(R5), R5.base)
print("R2 == R4 ? %s" % (R2 == R4))
print("R1 == R5 ? %s" % (R1 == R5))
It gives us the result
Received base = apple
Number of instances = 2
Received base = None
Number of instances = 2
Received base = banana
Number of instances = 3
Received base = None
Number of instances = 3
Received base = apple
Number of instances = 4
2167043940208 apple
2167043940256 None
2167043939968 banana
2167043940256 None
2167043939872 apple
R2 == R4 ? True
R1 == R5 ? False
Is nice to know that __init__ will be always called before the return of the __new__, even if you don't call it (in commented part) or you return an object that already exists.

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)

Class design: Last Modified

My class:
class ManagementReview:
"""Class describing ManagementReview Object.
"""
# Class attributes
id = 0
Title = 'New Management Review Object'
fiscal_year = ''
region = ''
review_date = ''
date_completed = ''
prepared_by = ''
__goals = [] # List of <ManagementReviewGoals>.
__objectives = [] # List of <ManagementReviewObjetives>.
__actions = [] # List of <ManagementReviewActions>.
__deliverables = [] # List of <ManagementReviewDeliverable>.
__issues = [] # List of <ManagementReviewIssue>.
__created = ''
__created_by = ''
__modified = ''
__modified_by = ''
The __modified attribute is a datetime string in isoformat. I want that attribute to be automatically to be upated to datetime.now().isoformat() every time one of the other attributes is updated. For each of the other attributes I have a setter like:
def setObjectives(self,objectives):
mro = ManagementReviewObjective(args)
self.__objectives.append(mro)
So, is there an easier way to than to add a line like:
self.__modified = datetime.now().isoformat()
to every setter?
Thanks! :)
To update __modified when instance attributes are modified (as in your example of self.__objectives), you could override __setattr__.
For example, you could add this to your class:
def __setattr__(self, name, value):
# set the value like usual and then update the modified attribute too
self.__dict__[name] = value
self.__dict__['__modified'] = datetime.now().isoformat()
Perhaps adding a decorator before each setter?
If you have a method that commits the changes made to these attributes to a database (like a save() method or update_record() method. Something like that), you could just append the
self.__modified = datetime.now().isoformat()
just before its all committed, since thats the only time it really matters anyway.

Categories