Why are there two elements in the collection? - python

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?

Related

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)

Class instances overwrite attributes

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

comparing a number with a prefix in a class in python

I am working on a small module.
I have a class called pricelist. It contains the attributes prefix and price.
class pricelist:
def setPrefix(self,prefix):
self.prefix = prefix
def setPrice(self,price):
self.price = price
def getPrefix(self):
return self.prefix
def getPrice(self):
return self.price
def getPrefixLength(self):
return len(self.prefix)
I have created a list of pricelist objects.
now i want to perform the operation, where when i give a phone number as input, i want to find prefix of the number and the corresponding price related to the prefix.
Example:
prefix price
46 2.0
44 3.0
.
.
.
.
when i give the input say "46 7223232323", it should return the price corresponding to it.
I am new to python and python classess, so can you please help me out with the logic of this
Keep the prefixes and prices in a dict:
self.data = {"46": 2.0,"44":3.0}
inp = "46 7223232323"
get_pre = inp.split()[0]
print (self.data.get(get_pre))
2.0
class Pricelist:
def __init__(self):
self.data = {"46": 2.0,"44":3.0}
p = Price_list()
inp = "46 7223232323"
get_pre = inp.split()[0]
print (p.data.get(get_pre,"Sorry that is an invalid prefix")) # if the prefix does not exist, it will output "Sorry that is an invalid prefix"
You can access attributes directly without getters and setters:
class Price_list:
def __init__(self,prefix,price):
self.prefix = prefix
self.price = price
self.pre_len = len(self.prefix)
p = Price_list("46", "4.99")
print (p.prefix, p.price, p.pre_len)
You can use data as a class attribute and add all instance attributes to it:
class Price_list:
data = {}
def __init__(self, prefix, price):
self.prefix = prefix
self.price = price
self.pre_len = len(self.prefix)
p = Price_list("46", "4.99")
p.data[p.prefix] = [p.price]
p1 = Price_list("44", "3.99")
p1.data[p1.prefix] = [p1.price]

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)

Python Error: 'finalStore' object has no attribute 'name'

I'm working with Inheritance in python but i'm getting an error i don't know how to fix, 'finalStore' object has no attribute 'marone'. I get this when i try create an object.
from ClassFile import studStore
class finalStore (studStore):
grandAve = 0
numStu = 0
def __init__(self, name, marone, martwo, marthree, marfour, corone, cortwo, corthree, corfour):
studStore.__init__(self, name, marone, martwo, marthree, marfour)
self.corone = corone
self.cortwo = cortwo
self.corthree = corthree
self.corfour = corfour
finalStore.numStu += 1
self.holder = finalStore.numStu
self.average = (marone + martwo + marthree + marfour)/4
finalStore.grandAve += self.average
self.storit = finalStore.grandAve
My initializing for the child class
class studStore:
def __init__(self, name, marone, martwo, marthree, marfour):
self.newname = name
self.Ave = 0
self.marone = marone
self.martwo = martwo
self.marthree = marthree
self.marfour = marfour
And the initializing for the parent class. My main line is just a loop where i create multiple objects for but it errors on this line:
listIn.append(finalStore(name, gradeone, gradetwo, gradethree, gradefour, courseOne, courseTwo, courseThree, courseFour))
I'm not sure what the error is but I have a similar program that works, I'm just not using the from * import *
I'm outputting it like this
for i in range (0,len(listIn)):
print(str(listIn[i].returnName()).ljust(20," "), end = " ")
print(str(listIn[i].returnOne()).ljust(20, " "))
print(str(listIn[i].returnTwo()).ljust(20, " "))
print(str(listIn[i].returnThree()).ljust(20, " "))
print(str(listIn[i].returnFour()).ljust(20, " "))
Your call to the super class's init function is incorrect. Here is how you should do it:
class finalStore(studStore):
def __init__(self, name, ...):
super(finalStore, self).__init__(name, marone, ...)

Categories