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

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)

好的,这就是我要做的。

试试这个:

#!/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()

注意,代码的结尾。

使用initializer设置默认值,然后创建一个方法来设置或更新。然后为了便于阅读,我为 set/update 你的 self.variables 创建了一个单独的方法,然后将你的字典拆分为一个变量,然后打印出来。

结果:

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

有用的提示:尝试使用带有语法高亮显示的文本编辑器,因为这将帮助您学习并记住格式化,为您最大限度地减少这些错误 =)

我还在学习自己,我相信你会得到更多有趣的答案,none更少,这就是我对你的代码示例所做的。

你有几个错误,但没有必要走@JayRizzo 走的路:

displayInformation 方法中有一个拼写错误:InterestArea 应该是 interestArea - 注意首字母小写 i。除此之外,class 的定义很好。

主要问题是class的使用:你应该使用它的方式是实例化class(即定义一个对象那种类型):

emp =  MyIntroduction("Terex", "92", "BE", "MA", "Sports")

然后让对象调用 displayInformation() 方法来显示自身:

emp.displayInformation()

请注意,__init__ 不应在实例化时显式出现,并且 self 不应显式出现在 class 之外:当对象调用 class 方法时(例如 emp.displayInformation(),对象被隐式传递给方法。这就是 self 在 class 定义中所指的:调用 class 方法的对象。