I wrote this script:
class MonDictionnaire:
def __init__(self):
self.dictionnaire = {}
def __add__(self, objetàajouter):
nouvelle_valeure = MonDictionnaire()
nouvelle_valeure.dictionnaire = self.dictionnaire
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()
then I wanted two objects in this class like:
>>>>fruit = MonDictionnaire()
>>> fruit.dictionnaire["pommes"] = 13
>>> fruit.dictionnaire["poires"] = 12
>>> fruit.dictionnaire["pruneau"] = 11
>>> legume = MonDictionnaire()
>>> legume.dictionnaire["poireau"] = 10
>>> legume.dictionnaire["panet"] = 9
then I just wanted to add my two objects like:
>>> fruit = fruit + legume
but the shell return me the following error message:
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
fruit = fruit + legume
File "D:\Python\Dictionnaire.py", line 9, in __add__
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items())
AttributeError: 'MonDictionnaire' object has no attribute 'items'
and I don't get why as my created class is a dictionnary???!!!
thank you so much for helping me!!!
Looks like your issue is with this line:
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()
When you call: fruit = fruit + legume your class is trying to call .items() on legume. I think this change should work as you expect:
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.dictionnaire.items()
You have defined the instance attribute:
self.dictionnaire = {}
whereas in objetàajouter.items() you're trying to get the items method of the instance itself, which is not present.
You need to explicitly specify the attribute:
objetàajouter.dictionnaire.items()
Also, were you meant to subclass dict?
Related
i'm getting NameError: for the following code...
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(int(i[0]))
print(RD)
def ReleaseDeal(a):
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
i'm getting following errors...
Traceback (most recent call last):
File "example.py", line 3, in <module>
RD = ReleaseDeal(int(i[0]))
NameError: name 'ReleaseDeal' is not defined
please help me on this , Thanks in advance..
You got several errors:
Define something before you reference to it
The parameter does not apply to the used one in ReleaseDeal
Concatenation of int to string fails.
def ReleaseDeal(no): # this was a, is has to be no and string
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(i[0])
print(RD)
Maybe type hints are useful for you ;-) https://docs.python.org/3/library/typing.html#typing.ClassVar Then you can say something like
ReleaseDeal(no: str) -> str:
So you want to get no of type string and return string.
Im trying to understand why I cannot access the methods on an object that is instantiated inside of a class. For example i'm attempting to build a script that utilizes the python-pptx library and I want to wrap the entire slide creation within a class to abstract it and make it a bit more reusable based on my configuration.
class Builder():
def __init__(self, template='template.pptx', output_file='out.pptx'):
self.cust_name = ''
self.author = ''
self.job_title = ''
self.present_date = ''
self.assessment_type = ''
self.template = template
self.agenda = ['Overview','Resources']
self.outfile = output_file
self.prs = Presentation('template.pptx') <--- This is what im referring to.
def addAgendaSlide(self):
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA]) <-- When trying to access this
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[10].text = 'A test Agenda slide'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
for para in self.agenda:
p = agenda_slide.placeholders[15].text_frame.add_paragraph()
p.text = para
Traceback (most recent call last):
File "test.py", line 19, in <module>
test.addAgendaSlide()
File "/dev/pythonpptx/DocMaker/Slides.py", line 89, in addAgendaSlide
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
AttributeError: 'Presentation' object has no attribute 'add_slide'
If I use the same bits of code outside the class it works fine. I do have other methods in the class that are fine, it seems to be my implementation of the Presentation() bit that is messing me up.
The following works fine:
prs = Presentation('template.pptx')
agenda_slide = prs.slides.add_slide(prs.slide_layouts[AGENDA])
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
prs.save('out.pptx')
I think your problem is you are forgetting to add slides as follows:
agenda_slide = self.prs.slides.add_slide(self.prs.slide_layouts[AGENDA])
instead of
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
I have the following lines of code in project A
#filename : mod_dates
#Handles date calculations etc
import datetime
class datecalcs:
def __init__(self):
self.__menuChoice = 0
self.__datemonth = "not set"
self.__effectivedate = ""
self.__year = 0
self.__month = 0
return None
#
def interestcouponpaydates(self,effectivedate,couponday):
self.__effectivedate = effectivedate
year, month, day = map(int,self.__effectivedate.split('-'))
print(year)
print(month)
return self.__effectivedate
When I call them from another file with
import mod_dates
import datetime
import modcalinputs
datesclass = mod_dates.datecalcs()
calcInputs = modcalinputs.calcinputs()
#Get the coupon date
interestdateeffective = calcInputs.interestdateffective()
interestdatecoupon = calcInputs.interestdatecoupon()
x = datesclass.interestcouponpaydates(interestdateeffective,interestdatecoupon)
print(x)
However this returns an error on the x = datesclass... line of
year, month, day = map(int,self.__effectivedate.split('-'))
raises:
> AttributeError: 'datetime.date' object has no attribute 'split'
When I run from a similar project to the same line with the same syntax it works fine. Any ideas on what I am doing wrong?
Looks like something is assigning a datetime.date object to __effectivedate. You can't call split() on that:
>>> import date
>>> d = d = datetime.date(2012,3,12)
>>> d.split('-')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'split'
You can convert it to a string and split:
>>>str(d).split('-')
['2012', '03', '12']
I am new to Python and working on a class for storing meaningful data pieces about books. I have started as follows:
class BookDisplay:
def __init__(self, _name, _isbn, _price, _picture, _link):
self.name = _name
self.isbn = _isbn
self.price = _price
self.picture = _picture
self.link = _link
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
name = ""
isbn = ""
price = 0.0
picture = "" #a URL
link = ""
xmlString = ""
I thought this __init__ method would just be able to call MakeXMLString, which I defined in the same file (bookdisplay.py), right below the BookDisplay class:
def MakeXMLString(_name, _isbn, _price, _picture, _link): #python multi-line syntax
xmlString = "<name>" + _name + "</name>" \
+ "<isbn>" + _isbn + "</isbn>" \
+ "<price>" + str(_price) + "</price>" \
+ "<picture>" + _picture + "</picture>" \
+ "<link>" + _link + "</link>"
return xmlString
Originally, I actually had MakeXMLString as a method within the class, like this:
def MakeXMLString(self):
self.xmlString = "<name>" + self.name + "</name>" \
+ "<isbn>" + self.isbn + "</isbn>" \
+ "<price>" + str(self.price) + "</price>" \
+ "<picture>" + self.picture + "</picture>" \
+ "<link>" + self.link + "</link>"
In that case, __init__ contained this call:
self.xmlString = self.MakeXMLString()
In both cases, when trying to instantiate BookDisplay from another file:
from bookdisplay import BookDisplay
...
...
thumbnails = []
...
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
...I get the following global name error (this traceback in particular for the not-within-class function):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "search.py", line 30, in ebaySearch
handleDocument(doc)
File "search.py", line 59, in handleDocument
handleItems(items, outputFile)
File "search.py", line 102, in handleItems
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
File "bookdisplay.py", line 15, in __init__
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
NameError: global name 'MakeXMLString' is not defined
What am I missing here? From what I can tell, MakeXMLString is perfectly accessible to the class.
when you defined MakeXMLString as a method, it is not returning anything so
self.xmlString = self.MakeXMLString()
will overwrite self.xmlString and make it point to the method itself.
With the way you have it defined now, MakeXMLString is not accessible from the other file, so you have to manually import it as well by doing:
from bookdisplay import BookDisplay, MakeXMLString
EDIT:
upon rereading, you aren't calling MakeXMLString from the other file, so the error is in bookDisplay.py; make sure
def MakeXMLString()
is on the same indent level as the class definition, otherwise it'll be interpreted as a method.
I want to serialize a dictionary to JSON in Python. I have this 'str' object has no attribute 'dict' error. Here is my code...
from django.utils import simplejson
class Person(object):
a = ""
person1 = Person()
person1.a = "111"
person2 = Person()
person2.a = "222"
list = {}
list["first"] = person1
list["second"] = person2
s = simplejson.dumps([p.__dict__ for p in list])
And the exception is;
Traceback (most recent call last):
File "/base/data/home/apps/py-ide-online/2.352580383594527534/shell.py", line 380, in post
exec(compiled_code, globals())
File "<string>", line 17, in <module>
AttributeError: 'str' object has no attribute '__dict__'
How about
s = simplejson.dumps([p.__dict__ for p in list.itervalues()])
What do you think [p.__dict__ for p in list] does?
Since list is not a list, it's a dictionary, the for p in list iterates over the key values of the dictionary. The keys are strings.
Never use names like list or dict for variables.
And never lie about a data type. Your list variable is a dictionary. Call it "person_dict` and you'll be happier.
You are using a dictionary, not a list as your list, in order your code to work you should change it to a list e.g.
list = []
list.append(person1)
list.append(person2)