Python Forum
attribute error instead of correct output
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
attribute error instead of correct output
#1
Hi,

When running this code i should get " Hallo Zelda" but instead i get an error message. What am i doing wrong?

Any input is much appreciated!

>>> class MyClass:
    Greeting = ""
    
>>> def SayHello(self):
    print("Hallo {0}".format(self.Greeting))
    
>>> MyClass.Greeting = "Zelda" 
>>> MyClass.Greeting
'Zelda'
>>> MyInstance = MyClass()
>>> MyInstance.SayHello()
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'SayHello'
>>> 
Reply
#2
You need to indent. Also the interpreter is thinking you are done defining class when press <enter> after an empty line. If you want to write classes use the file editor, not the shell.
Reply
#3
In your code, def SayHello is not indented (and must be)
this is a difficult code to write interactively, a better example (using a script file) below (includes a default greeting)

MyClass.py:
class MyClass:
    def __init__(self, greeting='there'):
        self.greeting = greeting

    def say_hello(self):
        print(f"Hello {self.greeting}")

def main():
    myinstance = MyClass()
    myinstance.say_hello()
    myinstance.greeting = 'Zelda'
    myinstance.say_hello()

if __name__ == '__main__':
    main()
Output:
Hello there Hello Zelda
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error with output djprasanna 1 552 Nov-28-2023, 06:40 PM
Last Post: deanhystad
  Error: audioio has no attribute 'AudioOut' netwrok 3 659 Oct-22-2023, 05:53 PM
Last Post: netwrok
  cx_oracle Error - AttributeError: 'function' object has no attribute 'cursor' birajdarmm 1 2,399 Apr-15-2023, 05:17 PM
Last Post: deanhystad
  how can I correct the Bad Request error on my curl request tomtom 8 5,089 Oct-03-2021, 06:32 AM
Last Post: tomtom
  Getting 'NoneType' object has no attribute 'find' error when WebScraping with BS Franky77 2 5,286 Aug-17-2021, 05:24 PM
Last Post: Franky77
  Attribute Error received not understood (Please Help) crocolicious 5 2,701 Jun-19-2021, 08:45 PM
Last Post: crocolicious
  error in scapy attribute 'haslayer' evilcode1 5 6,559 Mar-02-2021, 11:19 AM
Last Post: evilcode1
  Four sequential bytes; Need to remove high order bit in each to get correct output GrandSean 5 2,956 Feb-06-2021, 07:17 PM
Last Post: GrandSean
  attribute error stumped on how to fix it. hank4eva 7 4,787 Aug-11-2020, 04:47 AM
Last Post: hank4eva
  Attribute Error - trying to create a pixel array out of PNG files The_Sarco 1 2,019 Apr-29-2020, 07:10 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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