python - 类定义中定义的函数导致的 AttributeError
问题描述
我正在尝试学习如何在 Python 中定义类,首先创建一个非常基本的示例:
class CustomClass:
def print_class(self):
print(self)
CustomClass = 'Hello World'
CustomClass.print_class()
然而,当我运行它时,我得到了错误:
AttributeError: 'str' object has no attribute 'print_class'
我不想尝试访问或定义此类的某些属性。我想运行定义类时定义的函数。有人可以指出我做错了什么吗?
解决方案
你想用这个语句做什么:CustomClass = 'Hello World'
如果要实例化该类的对象,则需要执行以下操作:
name_of_object = CustomClass() # create an object
name_of_object.print_class() # this will call the method in that class
推荐阅读
- css - 在 CSS3 响应式字体标题上解析来自 W3C 验证器的错误
- c# - VS 在启动调试器时卡在“正在加载”
- algorithm - 最小硬币找零问题 - 最小公倍数
- reactjs - redux-thunk 重复 redux-api-middleware 操作,直到超时或设置状态变量
- scala - 如何在Scala中访问嵌套映射中的键值
- java - 如何在editTextView中按ID显示SQL数据?
- pandas - 如何分离季度和年度数据
- javascript - 使用 Ajax POST 到 REST 服务失败
- python - 如何获取项目列表并使用它们创建条件
- css - 如何让表格宽度在我的一个媒体查询中移动