Jump to content

Python: Error while creating array of Object

Featured Replies

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)
  • Author

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.

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.