首页 > 解决方案 > 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'

标签: pythonclassattributeerror

解决方案


压痕会给您带来问题吗?我在修复缩进后运行了你的代码,它运行良好。您的__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())

推荐阅读