Bgraham
Bgraham

Reputation: 27

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'

Upvotes: 1

Views: 65

Answers (2)

DanDeg
DanDeg

Reputation: 316

With fixed indentation:

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

Upvotes: 0

TaxpayersMoney
TaxpayersMoney

Reputation: 689

Is the indentation causing you a problem? I ran your code after fixing the indentation and it worked fine. Your __init__ function just needed indenting.

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

Upvotes: 1

Related Questions