简体   繁体   English

python:在模块之间设置属性

[英]python: setting attributes from module to module

Im teaching myself python and I've come upon a snag in a simple game project I'm working on. 我正在自学python,在我正在研究的一个简单游戏项目中遇到了麻烦。

I would like to keep the players stats in a different module from the rooms that are being run by the game engine. 我想将玩家统计信息与游戏引擎正在运行的房间保持在不同的模块中。 Problem is when I try to set a Player attribute from a different module, it doesn't save the new attribute and instantiates the original attribute. 问题是当我尝试从其他模块设置Player属性时,它不会保存新属性并实例化原始属性。

here is the Player class in the entities module 这是entities模块中的Player

class Player(object):

    def __init__(self):

        self.name = ' '
        self.hp = 0
        self.current_hp = 0
        self.strength = 0
        self.dexterity = 0
        self.constitution = 0

And here is how im trying to manipulate and test the attributes in the rooms module 这就是我试图操纵和测试rooms模块中的属性的方法

class CharacterCreation(Scene):
    def enter(self):
        character = entities.Player()
        character.hp = 10
        print character.hp
        return 'barracks'

class Barracks(Scene):
    def enter(self):
        character = entities.Player()
        print character.hp
        return 'shop'

When I test this with the rest of my code, here is what I get. 当我用其余的代码测试时,这就是我得到的。

-------------------------------------------------------------------------------


10
-------------------------------------------------------------------------------


0
-------------------------------------------------------------------------------

So what am I missing here? 那我在这里想念什么? I thought I could set that attribute using = but it seems I'm mistaken? 我以为可以使用=设置该属性,但似乎我弄错了? the first time I did it, it worked, but then how do i get python to set the new value of hp to 10? 第一次这样做,它奏效了,但是然后我如何让python将hp的新值设置为10?

You're creating a new Player object in each scene, changing its attributes, and then throwing it away . 您正在每个场景中创建一个新的Player对象,更改其属性,然后将其扔掉

You should be explicitly passing one single player into each scene: 您应该在每个场景中明确地传递一个玩家:

def enter(self, player):
   ... do something with player ...

It looks like you're creating a new Player instance on every enter method... 看来您在每个enter方法上都创建了一个新的Player实例。

If you're going to have only one player in the game, you could have it as a global variable (usually not very good idea) or even better, as a singleton class: http://blog.amir.rachum.com/post/21850841339/implementing-the-singleton-pattern-in-python 如果您只有一个玩家参与游戏,则可以将其作为一个全局变量(通常不是一个好主意),甚至可以作为一个单例类更好: http : //blog.amir.rachum.com/ post / 21850841339 /在python中实现单例模式

I made some tweakings to the code. 我对代码进行了一些调整。 It adds the PlayerPool class (which is more like a cache, actually). 它添加了PlayerPool类(实际上更像是一个缓存)。 It may give you some ideas :) 它可能会给你一些想法:)

#!/usr/bin/env python
#http://stackoverflow.com/questions/14629710/python-setting-attributes-from-module-to-module/14629838#14629838

class Player(object):
    def __init__(self):
        self.name = ' '
        self.hp = 0
        self.current_hp = 0
        self.strength = 0
        self.dexterity = 0
        self.constitution = 0

class PlayerPool(object):
    _players = dict()

    @classmethod
    def getPlayerByName(cls, name):
        if not name in cls._players:
            newPlayer = Player()
            newPlayer.name = name
            cls._players[newPlayer.name] = newPlayer
        return cls._players[name]


class Scene(object):
    pass

class CharacterCreation(Scene):
    def enter(self):
        character = PlayerPool.getPlayerByName("foobar-hero")
        character.hp = 10
        print "%s has %s points of hp" % (character.name, character.hp)
        return 'barracks'

class Barracks(Scene):
    def enter(self):
        character = PlayerPool.getPlayerByName("foobar-hero")
        print "%s has %s points of hp" % (character.name, character.hp)
        return 'shop'

if __name__ == "__main__":
    step1 = CharacterCreation()
    if step1.enter() == "barracks":
        step2 = Barracks()
        step2.enter()

That outputs: 输出:

borrajax@borrajax-comp:~/Tests/Python/Stack Overflow$ python ./players.py 
foobar-hero has 10 points of hp
foobar-hero has 10 points of hp

Welcome to python. 欢迎使用python。 I'm sure you'll find it has really cool features... such as the ability to return functions, or pass functions as parameters, inspect the classes defined in any module... Looks like things you could find useful. 我相信您会发现它确实具有很酷的功能……例如返回函数或将函数作为参数传递,检查任何模块中定义的类的能力……看起来您会发现有用的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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