Python Forum
File "<string>", line 19, in <module> error is related to what?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File "<string>", line 19, in <module> error is related to what?
#1
Hello,

I am trying to understand what is going on:

class Portfolio:
    def __int__(self):
        self.holdings = {}  #key = ticker, Value = number of shares
        
    def buy(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) + shares
        
    def sell(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) - shares
        
    def __iter__(self):
        return iter(self.holdings.items())
        
        
p = Portfolio()
p.buy('Alpha', 15)
p.buy('Beta', 23)
p.buy('Gamma', 9)
p.buy('Gamma', 20)
p.sell('Beta', 5)

for (ticker, shares) in p:
    print(ticker, shares)
According to the errors output:

Error:
Traceback (most recent call last): File "<string>", line 19, in <module> File "<string>", line 9, in buy AttributeError: 'Portfolio' object has no attribute 'holdings' >
I am missing a module? But which one?

Thank you
Reply
#2
My guess is you have a hidden character.
I tried your code from copy and paste and got the same error but, when I typed it in it worked as expected.

class Portfolio:
    def __init__(self):
        self.holdings = {}

    def buy(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) + shares

    def sell(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) - shares

    def __iter__(self):
        return iter(self.holdings.items())


p = Portfolio()
p.buy('Alpha', 15)
p.buy('Beta', 23)
p.buy('Gamma', 9)
p.buy('Gamma', 20)
p.sell('Beta', 5)

str_len = len(max(p)[0])

for (ticker, shares) in p:
    if len(ticker) < str_len:
        spacer = ' '*(str_len - len(ticker) + 2)
    else:
        spacer = ' '*2
    print(f'{ticker} {spacer} {shares}')
Output:
Alpha 15 Beta 18 Gamma 29
Frankduc likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
(Jan-26-2022, 04:41 PM)menator01 Wrote: My guess is you have a hidden character.
I tried your code from copy and paste and got the same error but, when I typed it in it worked as expected.

class Portfolio:
    def __init__(self):
        self.holdings = {}

    def buy(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) + shares

    def sell(self, ticker, shares):
        self.holdings[ticker] = self.holdings.get(ticker, 0) - shares

    def __iter__(self):
        return iter(self.holdings.items())


p = Portfolio()
p.buy('Alpha', 15)
p.buy('Beta', 23)
p.buy('Gamma', 9)
p.buy('Gamma', 20)
p.sell('Beta', 5)

str_len = len(max(p)[0])

for (ticker, shares) in p:
    if len(ticker) < str_len:
        spacer = ' '*(str_len - len(ticker) + 2)
    else:
        spacer = ' '*2
    print(f'{ticker} {spacer} {shares}')
Output:
Alpha 15 Beta 18 Gamma 29

Thanks menator for solving that. Which i knew where it came from, from the start.
Reply
#4
__init__ not __int__. Hard to see because you often see what you expect to see, not what is really there.

If an attribute created in __init__() is not in the object, test if __init__() is called.
class Portfolio:
    def __int__(self):
        print("Enter __init__()")
        self.holdings = {}  #key = ticker, Value = number of shares
        print("Leave __init__()")
When I created a Portfolio object it didn't print anything. That means __init__() wasn't called. Knowing that it didn't take long to find the error.
Frankduc and BashBedlam like this post
Reply
#5
(Jan-26-2022, 07:29 PM)deanhystad Wrote: __init__ not __int__. Hard to see because you often see what you expect to see, not what is really there.

If an attribute created in __init__() is not in the object, test if __init__() is called.
class Portfolio:
    def __int__(self):
        print("Enter __init__()")
        self.holdings = {}  #key = ticker, Value = number of shares
        print("Leave __init__()")
When I created a Portfolio object it didn't print anything. That means __init__() wasn't called. Knowing that it didn't take long to find the error.

I saw with the Python tutor https://pythontutor.com/visualize.html#mode=display something was wrong with that part of the code: def __int__(self):

It also return AttributeError: 'Portfolio' object has no attribute 'holdings'

How to solve it is something else.
I am not sure what is going on here:

str_len = len(max(p)[0])
 
for (ticker, shares) in p:
    if len(ticker) < str_len:
        spacer = ' '*(str_len - len(ticker) + 2)
    else:
        spacer = ' '*2
    print(f'{ticker} {spacer} {shares}')
Menator spoke about a hidden character.
Reply
#6
Menator was wrong. It was a missing character, not a hidden character. He didn't see the method name was __int__ either.

What part of the code are you confused about? Be more specific.

Stop using "reply" all the time. Haven't you noticed that nobody uses it when replying to your posts? Use "Quick Reply" and if it is unclear what post you are replying to, reference the poster's name or copy/paste/quote the part you are referencing. Replying to everything ends up making really long threads that are annoying to read.
ibreeden likes this post
Reply
#7
But what is missing in the code to make that part work?

for (ticker, shares) in p:
    print(ticker, shares)
Anyway ill find out soon or later

thanks
Reply
#8
The thing that was missing was the second "i" in "__init__()". Your Portfolio class did not have an __init__() method because you made a mistake when typing the method name. Instead you wrote a __int__() method which was never used.

When you created a Portfolio object Python looked to see if the Portfolio class has an __init__() method. It did not because of your typing error. This resulted in the holdings dictionary never being created.

What is your question about this code?
for (ticker, shares) in p:
    print(ticker, shares)
If you fix the typing error in the Portfolio.__init__() method name the loop will work. If you don't fix the method name your program never reaches this point in the code because it crashes when you call Portfolio.buy().
Reply
#9
To say i tripled check and more to see if there was mistyping.

Its not this code it is the one provided by menator:

str_len = len(max(p)[0])
  
for (ticker, shares) in p:
    if len(ticker) < str_len:
        spacer = ' '*(str_len - len(ticker) + 2)
    else:
        spacer = ' '*2
    print(f'{ticker} {spacer} {shares}')
str is for string and len is for length (maximum(p)) Whatever i thought it was his solution to solve the mystery behind the absence of output and error returned.
When actually it is just a way to create a space between the porfolio stocks and prices in the output.
Sometimes i can be dense! Tongue

Thanks dean
Reply
#10
It's strange that you're seeing the identical network issue on two systems that are purportedly completely distinct from one another. It's possible that it was merely a coincidence. Nerdle is a fun and challenging way to sharpen your analytical and numerical prowess. Are you able to recall anything that altered itself about the same time that this phenomenon began to take place?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  trouble reading string/module from excel as a list popular_dog 0 417 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Need to replace a string with a file (HTML file) tester_V 1 762 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Getting last line of each line occurrence in a file tester_V 1 861 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,369 Sep-27-2022, 01:38 PM
Last Post: buran
  Inserting line feeds and comments into a beautifulsoup string arbiel 1 1,184 Jul-20-2022, 09:05 AM
Last Post: arbiel
  Pandas - error when running Pycharm, but works on cmd line zxcv101 1 1,360 Jun-18-2022, 01:09 PM
Last Post: snippsat
  Print to a New Line when Appending File DaveG 0 1,217 Mar-30-2022, 04:14 AM
Last Post: DaveG
  Find and delete above a certain line in text file cubangt 12 3,459 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,685 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  writelines only writes one line to file gr3yali3n 2 2,374 Dec-05-2021, 10:02 PM
Last Post: gr3yali3n

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020