Search code examples
attributeerror

AttributeError: 'str' object has no attribute 'name' while defining a class & calling it


class MyIntroduction:

    def __init__(self, name ,age,education,masters,interestArea):
      self.name = name
      self.age = age
      self.education = education
      self.masters = masters
      self.interestArea = interestArea
    def displayInformation(self):
        print({'name': self.name, 'a': self.age, 'e': self.education, 'M': self.masters, 'IA': self.InterestArea })

emp = { 'emp1': MyIntroduction.__init__("Terex", "92", "BE", "MA", "Sports")}
emp1.displayInformation(self)

Solution

  • Ok This is how I would do it.

    Try This:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    # =============================================================================
    """Doc PlaceHolder."""
    # =============================================================================
    
    
    class MyIntroduction():
        """Doc PlaceHolder."""
    
        def __init__(self):
            """Doc PlaceHolder."""
            self.name = ""
            self.age = ""
            self.education = ""
            self.masters = ""
            self.interestarea = ""
    
        def set_info(self, name, age, education, masters, interestarea):
            """Doc PlaceHolder."""
            self.name = name
            self.age = age
            self.education = education
            self.masters = masters
            self.interestarea = interestarea
    
        def displayinformation(self):
            """Doc PlaceHolder."""
            a = {'name': self.name,
                 'a': self.age,
                 'e': self.education,
                 'M': self.masters,
                 'IA': self.interestarea
                 }
            print(a)
    
    a = MyIntroduction()
    a.set_info('Jay', 453, 'SelfTaught', 'Making Stuff Up', 'Space Captain')
    a.displayinformation()
    

    Note, the ending of the code.

    Use the initializer to set the defaults, then create a method to set or update. Then for ease of reading I created a separate method to set/update your self.variables then split your dict to a variable then printed that.

    Results:

    python3 testy.py 
    {'name': 'Jay', 'a': 453, 'e': 'SelfTaught', 'M': 'Making Stuff Up', 'IA': 'Space Captain'}
    

    Helpful hints: Try using a text editor with syntax highlighting as that will help you learn and remember to format minimize these errors for you =)

    I'm still learning myself so, I have no doubt you will get more interesting answers, none the less, this is what I did with your code example.