简体   繁体   中英

TypeError: 'Piece' object is not subscriptable in Class type in Python

The Below code is used to name the possible xy-coordinates of chess pieces.

For instance: (1,1) for rook means the rook can move n 1 in x direction or n 1 in y-direction.

class Piece:
    def __init__(self,pawn1, rook2, knight3, bishop4, queen5, king6):
        self.rook2 = rook2
        self.pawn1 = pawn1
        self.knight3 =knight3
        self.bishop4 = bishop4
        self.king6 = king6
        self.queen5 = queen5

a = Piece((1,2),(0,1),(3,1),(1,1),(0,1,1),(0,1))

def rook_move(n):
    rook_move1 = n*rnd.random(a[2])
    return rook_move1
rook_move(3)

I get this error:

rook_move1 = n*rnd.random(a[2])
TypeError: 'Piece' object is not subscriptable

Can you please tell me what is the problem?

I tried both Lists and tuples. Trying to build a very basic, non-intuitive chess game.

a is a Piece object, not a list. so you can't use code like: a[2]

in general, this error

TypeError: 'X' object is not subscriptable

is there to tell you that x[i] (when x is an X object) does not exist, because x is not a list of any sort.

in your case, you probably want to be specific about which attribute of a you want, any of which are tuples!

for examle:

def rook_move(n):
    rook_move1 = n*rnd.random(a.rook2[2])
    return rook_move1
rook_move(3)

you see, a is not list-like, thus there is no such a thing as a[2]

but a.rook2 IS list-like indeed, (in that case we only have a.rook2[0] or a.rook2[1] but you get the point)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM