[ACCEPTED]-Calling a method from the same class-class

Accepted answer
Score: 13

Get rid of the class. Use plain functions 4 and module level variable for grid. The class 3 is not helping you in any way.

PS. If you 2 really want to call checkline from within the class, you'd 1 call Grid.checkline. For example:

class Foo:
    @staticmethod
    def test():
        print('Hi')
    @staticmethod
    def test2():
        Foo.test()

Foo.test2()       

prints

Hi
Score: 3

Syntax:

class_Name.function_Name(self)

Example:

Turn.checkHoriz(self)

0

Score: 1

A reworked example (hopefully showing a 1 better use of classes!)

import itertools

try:
    rng = xrange   # Python 2.x
except NameError:
    rng = range    # Python 3.x

class Turn(object):
    def __init__(self, players):
        self.players = itertools.cycle(players)
        self.next()

    def __call__(self):
        return self.now

    def next(self):
        self.now = self.players.next()

class Grid(object):
    EMPTY = ' '
    WIDTH = 10
    HEIGHT = 10
    WINLENGTH = 4

    def __init__(self, debug=False):
        self.debug = debug
        self.grid = [Grid.EMPTY*Grid.WIDTH for i in rng(Grid.HEIGHT)]
        self.player = Turn(['X','O'])

    def set(self, x, y):
        if self.grid[y][x]==Grid.EMPTY:
            t = self.grid[y]
            self.grid[y] = t[:x] + self.player() + t[x+1:]
            self.player.next()
        else:
            raise ValueError('({0},{1}) is already taken'.format(x,y))

    def get(self, x, y):
        return self.grid[y][x]

    def __str__(self):
        corner = '+'
        hor = '='
        ver = '|'
        res = [corner + hor*Grid.WIDTH + corner]
        for row in self.grid[::-1]:
            res.append(ver + row + ver)
        res.append(corner + hor*Grid.WIDTH + corner)
        return '\n'.join(res)

    def _check(self, s):
        if self.debug: print("Check '{0}'".format(s))
        # Exercise left to you!
        # See if a winning string exists in s
        # If so, return winning player char; else False
        return False

    def _checkVert(self):
        if self.debug: print("Check verticals")
        for x in rng(Grid.WIDTH):
            winner = self._check([self.get(x,y) for y in rng(Grid.HEIGHT)])
            if winner:
                return winner
        return False

    def _checkHoriz(self):
        if self.debug: print("Check horizontals")
        for y in rng(Grid.HEIGHT):
            winner = self._check([self.get(x,y) for x in rng(Grid.WIDTH)])
            if winner:
                return winner
        return False

    def _checkUpdiag(self):
        if self.debug: print("Check up-diagonals")
        for y in rng(Grid.HEIGHT-Grid.WINLENGTH+1):
            winner = self._check([self.get(d,y+d) for d in rng(min(Grid.HEIGHT-y, Grid.WIDTH))])
            if winner:
                return winner
        for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
            winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
            if winner:
                return winner
        return False

    def _checkDowndiag(self):
        if self.debug: print("Check down-diagonals")
        for y in rng(Grid.WINLENGTH-1, Grid.HEIGHT):
            winner = self._check([self.get(d,y-d) for d in rng(min(y+1, Grid.WIDTH))])
            if winner:
                return winner
        for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
            winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
            if winner:
                return winner
        return False

    def isWin(self):
        "Return winning player or False"
        return self._checkVert() or self._checkHoriz() or self._checkUpdiag() or self._checkDowndiag()

def test():
    g = Grid()
    for o in rng(Grid.WIDTH-1):
        g.set(0,o)
        g.set(Grid.WIDTH-1-o,0)
        g.set(Grid.WIDTH-1,Grid.HEIGHT-1-o)
        g.set(o,Grid.HEIGHT-1)
    print(g)
    return g

g = test()
print g.isWin()
Score: 0

Unlike java or c++, in python all class 6 methods must accept the class instance as 5 the first variable. In pretty much every 4 single python code ive seen, the object 3 is referred to as self. For example:

def reset(self):
    self.grid = [[0] * 10 for i in range(10)]

See http://docs.python.org/tutorial/classes.html

Note 2 that in other languages, the translation 1 is made automatically

Score: 0

Instead of operating on an object, you are 12 actually modifying the class itself. Python 11 lets you do that, but it's not really what 10 classes are for. So you run into a couple 9 problems

-You will never be able to make 8 multiple Grids this way

  • the Grid can't refer back to itself and e.g. call checkLine

After your grid definition, try 7 instantiating your grid and calling methods 6 on it like this

aGrid = Grid()
...
aGrid.checkLine()

To do that you, you first 5 need to modify all of the method definitions 4 to take "self" as your first variable and 3 in check, call self.checkLine()

def check(self):
    ...
    self.checkLine()
    ...

Also, your 2 repeated checking cries out for a FOR loop. You 1 don't need to write out the cases.

Score: 0

There are multiple problems in your class 26 definition. You have not defined array which 25 you are using in your code. Also in the 24 checkLine call you are sending a int, and 23 in its definition you are trying to subscript 22 it. Leaving those aside, I hope you realize 21 that you are using staticmethods for all 20 your class methods here. In that case, whenever 19 you are caling your methods within your 18 class, you still need to call them via your 17 class's class object. So, within your class, when 16 you are calling checkLine, call it is as Grid.checkLine That should 15 resolve your NameError problem.

Also, it 14 looks like there is some problem with your 13 module imports. You might have imported 12 a Module by name Grid and you have having 11 a class called Grid here too. That Python 10 is thinking that you are calling your imported 9 modules Grid method,which is not callable. (I 8 think,there is not a full-picture available 7 here to see why the TypeError is resulting)

The 6 best way to resolve the problem, use Classes 5 as they are best used, namely create objects 4 and call methods on those objects. Also 3 use proper namespaces. And for all these 2 you may start with some good introductory 1 material, like Python tutorial.

Score: 0

Java programmer as well here, here is how 1 I got it to call an internal method:

class Foo:
    variable = 0

    def test(self):
        self.variable = 'Hi'
        print(self.variable)

    def test2(self):
        Foo.test(self)

tmp = Foo()
tmp.test2()    

More Related questions