Suneeldatta Kolipakula
Suneeldatta Kolipakula

Reputation: 217

Why below part of python code is giving attribute error?

class TempClass():
def __init__(self,*args):
    for i in range(len(args)):
        self.number1=args[0]
        self.number2=args[1]
    print(self.number1,self.number2)

temp1=TempClass(10,20)

output: 10 20

class TempClass2():
def __init__(self,*args):
    for i in range(len(args)):
        self.number1=args[0]
        self.number2=args[1]
    print(self.number1)
    print(self.number1[0],self.number2)

temp2=TempClass2([10,20],40)

output : [10, 20]

class TempClass3():
def __init__(self,*args):
    for i in range(len(args)):
        self.number1[0]=args[0]
        self.number1[1]=args[1]
    print(self.number1)
temp3=TempClass3(10,20)

output: AttributeError: 'TempClass3' object has no attribute 'number1'

My question is in TempClass3 I tried to create a list by passing parameters to construct. why is it not possible??

Note: I tried doing this while learning OOps concepts in python.. please suggest me if my question itself is meaningless.

Upvotes: 0

Views: 33

Answers (3)

Samwise
Samwise

Reputation: 71454

In this code:

class TempClass3():
    def __init__(self,*args):
        for i in range(len(args)):
            self.number1[0]=args[0]
            self.number1[1]=args[1]
        print(self.number1)

you're attempting to access a list called self.number1 that doesn't exist yet. Instead you want to do something like:

class TempClass3():
    def __init__(self,*args):
        self.number1 = []  # create an empty list we can append to
        self.number1.append(args[0])
        self.number1.append(args[1])
        print(self.number1)

or maybe:

class TempClass3():
    def __init__(self,*args):
        self.number1 = [args[0], args[1]]  # create a list with two elements
        print(self.number1)

or, if you just want all the args instead of only the first two, simply:

class TempClass3():
    def __init__(self,*args):
        self.number1 = list(args)  # create a list from the contents of a tuple
        print(self.number1)

Upvotes: 0

norok2
norok2

Reputation: 26886

You first need to initialize self.number1 with [None] * 2 (or similar) before using it.

However, I would use args directly:

class TempClass3():
    def __init__(self,*args):
        self.number1 = list(args)
        print(self.number1)


temp3=TempClass3(10,20)

Upvotes: 1

JimmyCarlos
JimmyCarlos

Reputation: 1952

When you are calling self.number1[0]=args[0], you are asking python to first open the list self.number1 which doesn't exist, then find an element in this non-existent list.

If it doesn't exist but you pass it a value, like self.number1=args[0], python will create self.number1 and define self.number1 as args[0].

You could fix this by adding the line self.number1 = [0,0] at the start of tempclass3 so that the list already exists.

Upvotes: 0

Related Questions