简体   繁体   中英

How do you call a class's method when it is assigned to a variable and inside a function?

I have been working on a combat based game, and have assigned the stats of the characters to within classes. An example is below.

class elf():
    def __init__(self):
        self.attack = 1
        self.defense = 2
        self.speed = 3

def function():
    global player
    player = elf()

print(player)
print(player.attack)

How would you code this so I can access the variable from within a class which is in a function?

What you have written would work if you called your function before trying to access player :

class elf():
    def __init__(self):
        self.attack = 1
        self.defense = 2
        self.speed = 3

def function():
    global player
    player = elf()

function()
print(player)
print(player.attack)

But (likely) a better approach is to avoid global and return the elf instance.

class elf():
    def __init__(self):
        self.attack = 1
        self.defense = 2
        self.speed = 3

def function():
    return elf()


player = function()
print(player)
print(player.attack)

I realize you've provided a minimal example, so it's hard to say for sure that returning the instance is a better approach, but it's very likely, and will help reduce future errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM