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
  • 1
    You missed : after def set_first_name(self) Commented Oct 14, 2017 at 9:14
  • Oh man. Thanks and sorry for the spam. Commented Oct 14, 2017 at 9:18

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Yaroslav. I did your changes. After adding "self" as argument to set_first_name(), then it works perfectly. Thanks!
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.

2 Comments

No problem. Please upvote and accept as answer if it helped.
Also, beware of using the term 'class method'. It refers to a specific way of calliing a method. Info is here stackoverflow.com/q/12179271/4047084 if you're interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.