class Field: def __init__(self, ships=[]): self._ships = ships def shoot_at(self, tuple): pass def field_without_ships(self): pass def field_with_ships(self): lst = [[' ' for b in range(10)] for i in range(10)] print(lst) print(Field.field_with_ships()) 

With the tab, everything is fine just copied crookedly. Here is such a mistake

 TypeError: field_with_ships() missing 1 required positional argument: 'self' 

What is the problem and will it appear with other methods?

    1 answer 1

    3 options:

     field = Field() field.field_with_ships() 

    or

     @staticmethod def field_with_ships(): ... 

    or

     @classmethod def field_with_ships(cls): ... 

    The fact is that you have declared the field_with_ship method as a normal class method, and you need to call it on behalf of an instance of this class (thereby passing the instance as the first argument)

    If your class method does not imply the presence of an object or the attributes of the class itself, then it is better to declare it as @staticmethod . It will need to be written before each such method. If class attributes are used (common to all objects), then @classmethod , for example

     class A: x = 1 @classmethod def clsmethod(cls): print(cls.x) def __init__(self, y) self.y = y def objmetod(self): print(self.y) @staticmethod def statmethod(): print('Hello, world') A.clsmethod() # --> 1 A.statmethod() # --> Hello, world a = A(42) a.objmethod() # --> 42 
    • Is it necessary to sign staticmethod to all? Does @staticmethod work for all the function, what is the writing below it or only one? - lalalala
    • @lalalala added in the answer - andy.37