0

I have this code:

import random

class Player:

    def __init__(self):
        self.first_name = set_first_name()

    def set_first_name(self)
        List = open("player/first_names.txt").readlines()
        self.first_name = random.choice(List)

As you can see, I would like to set first name randomly from a text file. But I receive this error:

def set_first_name(self) ^ SyntaxError: invalid syntax

I assume it is not possible to call a class method within the initialisation of a class instance. At least not the way I am doing it. Could sombody give me a quick hint? I suppose there is an easy fix to this.

Thanks

2 Answers2

1

Your method is not a class method, you are simply missing the semi-colon from the end of your def line of the set_first_name method.

Stuart Buckingham
  • 1,574
  • 16
  • 25
1

First of all as was allready mentioned - you missed : in define line. Second: even if you fix that - you will get NameError because set_first_name is not in global scope. And for last - set_first_name doesn't returns anything, so you will get first_name as None.

Assuming that, right version of your code should look like:

import random

class Player:

    def __init__(self):
        self.first_name = self.set_first_name()

    @staticmethod
    def set_first_name():
        List = open("player/first_names.txt").readlines()
        return random.choice(List)
Yaroslav Surzhikov
  • 1,568
  • 1
  • 11
  • 16