python - Printing a class attribute
问题描述
Hi there I have the following code and I'm trying to print the object position, I am completely new to python & coding so need a bit of help! This is the code I have;
class object:
def __init__(self, x, y, z, vx, vy, vz):
self.x = x
self.y = y
self.z = z
self.vx = vx
self.vy = vy
self.vz = vz
def position(self):
return '{} {} {}'.format(self.x, self.y, self.z)
obj_1 = object(random.random(), random.random(), random.random(), 0, 0, 0)
print(obj_1.position())
I get the following error message:
AttributeError: 'object' object has no attribute 'position'
解决方案
压痕会给您带来问题吗?我在修复缩进后运行了你的代码,它运行良好。您的__init__
函数只需要缩进。
import random
class object:
def __init__(self, x, y, z, vx, vy, vz):
self.x = x
self.y = y
self.z = z
self.vx = vx
self.vy = vy
self.vz = vz
def position(self):
return '{} {} {}'.format(self.x, self.y, self.z)
obj_1 = object(random.random(), random.random(), random.random(), 0, 0, 0)
print(obj_1.position())
推荐阅读
- javascript - 在 drawImage IOS Safari 上使用视频元素的替代方法
- django - Django - 通过多对多上最近的表行加入
- hyperlink - RTF 中的内部超链接
- c++ - 为什么那里不调用普通函数?
- javascript - 在 passport.authenticate successRedirect 中使用条件
- shopify - 在页面模板中创建的 Shopify/liquid 代码段未在产品模板中正确加载
- keyboard-shortcuts - 是否有加速器关键解决方案来赋予 TrackBar 焦点
- apache-kafka - 如何在 Windows 中设置 Kafka 属性(在哪些属性文件中)并监控 Kafka 集群运行状况?
- javascript - JS按特定属性映射对象数组
- python - 如何使python进程访问所有内存?