Jump to content

Python: Error while creating array of Object


zak100

Recommended Posts

import numpy as np
class CPieces:
   pieceIndex=0;
   def __init__(self, pieceIndex):
       if (pieceIndex<8):
         self.pieceIndex = pieceIndex
       else:
         self.pieceIndex = pieceIndex


class B:
    Matrix = np.empty((8, 8))
    Matrix.fill(0)
    def __init__(self, n):
        self.n=n
        CPieces.pieces = []#no error if commented
        for i in range(n): #no error if commented
           CPieces.pieces.append = CPieces(self, i)#no error if commented

    def display(self, n):
        print(n)

    def main(self):
        n=8
        self.display(n)

if __name__ == "__main__":
    objB = B(8)
    objB.main()

Hi, Following is the output. If I remove th elines which have associated comments, I won't get error, please guide me.

Quote

Traceback (most recent call last):
  File "/home/zulfi/PycharmProjects/AIHW/GameProjTest.py", line 28, in <module>
    objB= B(8)
  File "/home/zulfi/PycharmProjects/AIHW/GameProjTest.py", line 18, in __init__
    CPieces.pieces.append = CPieces(self, i)#no error if commented
TypeError: __init__() takes 2 positional arguments but 3 were given

Zulfi.

Hi,

I removed the self from:

but I am still getting error:

Quote

Traceback (most recent call last):
  File "/home/zulfi/PycharmProjects/AIHW/GameProjTest.py", line 28, in <module>
    objB = B(8)
  File "/home/zulfi/PycharmProjects/AIHW/GameProjTest.py", line 18, in __init__
    CPieces.pieces.append = CPieces(i)#no error if commented
AttributeError: 'list' object attribute 'append' is read-only

CPieces.pieces.append = CPieces( i)
Link to comment
Share on other sites

Hi,
I think I have solved that problem:

import numpy as np
class CPieces:
   pieceIndex=0;
   def __init__(self, pieceIndex):
       if (pieceIndex<8):
         self.pieceIndex = pieceIndex
       else:
         self.pieceIndex = pieceIndex


class B:
    Matrix = np.empty((8, 8))
    Matrix.fill(0)
    def __init__(self, n):
        self.n=n
        CPieces.pieces = []#no error if commented
        obj1 =  CPieces(0)
        obj2 =  CPieces(1)
        CPieces.pieces.append(obj1)
        CPieces.pieces.append(obj2)

    def display(self, n):
        print(n)

    def main(self):
        n=8
        self.display(n)

if __name__ == "__main__":
    objB = B(8)
    objB.main()

Zulfi.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.