首页 > 解决方案 > 类定义中定义的函数导致的 AttributeError

问题描述

我正在尝试学习如何在 Python 中定义类,首先创建一个非常基本的示例:

class CustomClass:
    def print_class(self):
        print(self)

CustomClass = 'Hello World'
CustomClass.print_class()

然而,当我运行它时,我得到了错误:

AttributeError: 'str' object has no attribute 'print_class'

我不想尝试访问或定义此类的某些属性。我想运行定义类时定义的函数。有人可以指出我做错了什么吗?

标签: pythonfunctionclassattributes

解决方案


你想用这个语句做什么:CustomClass = 'Hello World'

如果要实例化该类的对象,则需要执行以下操作:

name_of_object = CustomClass() # create an object

name_of_object.print_class() # this will call the method in that class

推荐阅读