python - 打印类属性

标签 python class attributeerror

您好,我有以下代码,我正在尝试打印对象位置,我对 python 和编码完全陌生,所以需要一些帮助!这是我的代码;

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())

我收到以下错误消息:

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())

关于python - 打印类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52761039/

相关文章:

javascript - 将一系列时间序列化为有意义的数据的最佳方法

没有重复数字的Python列表

class - 编写 TypeScript 装饰器以始终将类方法绑定(bind)到 'this'

c++ - 如何将一个类中指向另一个类的指针复制到 C++ 中的另一个指针?

python - 在运行时更改 python mro

python - 返回BeautifulSoup属性错误: 'NoneType' object has no attribute 'encode'

python - AttributeError: 'Element' 对象没有属性 'findAll'

python - 通过 Flask 和 Nginx 提供静态文件?

python - 如何使用 Python 从 HTML 中提取它?

python - 方法 __setitem__ 上的 AttributeError