-3

I am relatively new to python. I am trying to make a (really bad) game in python to understand more about classes. I've mostly gotten there but i have to ask one question: How (if possible) do you call a class inside a function.

So say i have a class called Class and i want to "call" this class inside a function that is not part of any other class. Let's call this function Function. How would i go about doing it? I have searched on the internet but nothing. Classes are ridiculously confusing compared to anything else i've learnt. There's still so much i don't get.

Image of my problem

Hexzilian
  • 1
  • 3
  • Welcome to StackOverflow. Can you give us an example of the structure you want to access? A [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) would be really helpful. I know, it's work, and you actually want an answer, but it's important to put effort in questions you ask, so it's understood what you mean and the documentation is helpful for everyone that finds the question. – blkpingu Oct 12 '19 at 18:12
  • 1
    Please post code as *text* - so that people can try to run it without having to retype it all - rather than images. But in this case, the problem is obvious - you're using the name `player` to refer to both the class and the instance of the class. Change one of those - the convention is to use capitalized words for class names, so `player = Player()` would be good. – jasonharper Oct 12 '19 at 18:14
  • 1
    You understand exactly how it works; the problem in your code has nothing to do with classes. The problem is that the variable `player` has the same name as the class `player`, meaning you run into [the usual problem](https://stackoverflow.com/questions/41369408/how-to-change-a-variable-after-it-is-already-defined). The convention for Python code is to write `names_like_this` for local variables and `NamesLikeThis` for class names, which prevents them from conflicting. – Karl Knechtel Oct 12 '19 at 18:28
  • I understand the problem now. Thank you. – Hexzilian Oct 12 '19 at 18:34

1 Answers1

1

When you do

player = player(...)

what you're trying to do is create a variable called player of the class player.

However, python can't tell the difference. The moment you declare your intention to make a variable called player, python assumes that the name player will refer to that variable, not the class that is also called player. When you then try to call player, python gets confused, because you haven't assigned anything to the variable yet.

By convention (and you can even see this represented by the colors of each word below), we usually name classes with uppercase letters to avoid this situation:

class Player:
    ...

...


def create():
    player = Player(...)

because player and Player are not the same word, python no longer has any confusion.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53