简体   繁体   English

2个文件中的Python类[艰苦学习Python]

[英]Python Classes in 2 Files [Learn Python the Hard Way]

Hey guys, I'm currently completing Zed Shaw's "Learn Python the Hard Way" and I've been struggling with Exercise 43, which instructs the learner to make a game. 大家好,我目前正在完成Zed Shaw的“艰苦学习Python”,并且一直在练习43,该练习指导学习者编写游戏。 For simplicity, I am attempting to rewrite the previous exercise that has a class Game and some functions: 为简单起见,我试图重写之前的练习,该练习具有一个Game类和一些功能:
__init__ , play , death , and four more for each "room" in the game. __init__playdeath ,以及游戏中每个“房间”的另外四个。

I was able to copy and modify the code for various conditions, but I wanted to try to split the code in to two files: one file containing a class PrincessRoom to be the sole room for the game, and the other containing the bulk of the old code play and death . 我能够针对各种情况复制和修改代码,但我想尝试将代码分成两个文件:一个文件包含一个PrincessRoom类,作为游戏的唯一空间,另一个文件包含大部分的游戏空间。旧的代码playdeath

From ex43.py 来自ex43.py

from sys import exit
from random import randint
from ex43princess import PrincessRoom

class Game(object):

    def __init__(self, start):
        self.quips = [
            "You died. You suck.",
            "Hey, you died. Look at that.",
            "You lose. I win. End.",
        ]
        self.start = start

    def play(self):
        next = self.start

        while True:
            print "\n--------"
            room = getattr(self, next)
            next = room()

    def death(self):
        print self.quips[randint(0, len(self.quips)-1)]
        exit(1)

a_game = Game("princess")
a_game.play()

From ex43princess.py 来自ex43princess.py

class PrincessRoom(object):

    def __init__(self):
        pass

    def princess(self):
        print "text here"

        raw_input("> ")

        if raw_input == 1:
            return 'eat_it'
        else:
            return 'death'

    def eat_it(self):
        print "text here"

When I run the code, here's the error I get: 当我运行代码时,这是我得到的错误:

Traceback (most recent call last):
  File "ex43-2.py", line 29, in <module>
    a_game.play()
  File "ex43-2.py", line 21, in play
    room = getattr(self, next)
AttributeError: 'Game' object has no attribute 'princess'``

Now I'm not too solid on why the original code had a_game initialized with a_game = Game("princess") but I'm pretty sure it's directly related to why it has me use room = getattr(self, next) . 现在,我不是,为什么原来的代码做得太实a_game与初始化a_game = Game("princess")但我敢肯定它直接关系到它为什么有我使用room = getattr(self, next) But this is where my understanding falters. 但这就是我的理解力下降的地方。

If memory serves, it would appear that Game object isn't inheriting properly from ex43princess.py... right? 如果有记忆,似乎Game对象没有正确地继承自ex43princess.py ...对吗?

If any one could help me understand what is happening here I would be much appreciative. 如果有人可以帮助我了解这里发生的事情,我将不胜感激。

Thanks! 谢谢! Josh 乔希

Note: I'm not familiar with the book and hence with the context of the question, so my answer refers to the displayed code only 注意:我不熟悉这本书,因此不了解问题的内容,因此我的答案仅涉及显示的代码

The problem here isn't splitting the code to two files. 这里的问题不是将代码拆分为两个文件。 As far as I can see, the PrincessRoom class in its own file presents no real problem. 据我所知, PrincessRoom类在其自己的文件中没有出现任何实际问题。

Game can't find the princess method, and it doesn't have one. Game找不到princess方法,也没有。 Perhaps it should've inherited from PrincessRoom ? 也许它应该继承自PrincessRoom

That said, I'm not sure that it makes sense logically to inherit a class named Game from a class named PrincessRoom . 就是说,我不确定从名为PrincessRoom的类继承名为Game的类在逻辑上是否有意义。 A better approach IMHO would be aggregation - ie keep a collection of rooms as an instance variable of Game and access them through it. 恕我直言,更好的方法是聚合 -即保留房间的集合作为Game的实例变量,并通过Game访问它们。 Inheritance should be really reserved to is-a relations. 继承应该真正保留给is-a关系。 You should ask yourself, whether "Game is-a PrincessRoom" makes sense. 您应该问自己,“ Game is-a PrincessRoom”是否有意义。 It probably doesn't. 可能不是。 What does make sense is "Game has-a PrincessRoom", and has-a is represented by aggregation in OOP. 有意义的是“游戏has-a PrincessRoom”,而has-a由OOP中的聚合表示。

My quick and dirty version of exercise 43. Here . 我的快速和肮脏的版本锻炼43. 这里 The key is that you are just trying to instantiate the PrincessRoom objects but you can't do it with just a string like you are trying to do. 关键是您只是试图实例化PrincessRoom对象,但是不能像您尝试的那样仅使用字符串来实现它。

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

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