Search code examples
pythonclass-method

Setting initial instance parameter using a class method


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


Solution

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