简体   繁体   English

Python 3类无法从函数中打印

[英]Python 3 class not printing from function

So i'm trying to wrap my head around the __init__ and functions. 所以我想把头放在__init__和函数周围。 I am following the book, "Learn Python 3 the hard way" and I'm struggling to work out why my code won't print from a function but prints just fine from within the class. 我正在学习《用困难的方式学习Python 3》这本书,并且努力弄清楚为什么我的代码不能从函数中打印,而只能从类中打印。

from the code below: 从下面的代码:

class FirstScene(object):
    def enter(self):
        print("printing scene 1")

class SecondScene(object):
    pass

class Map(object):

    scenes = {
        "scene_one": FirstScene(),
        "scene_two": SecondScene()
    }

    def __init__(self, scene):
        self.scene = scene

game_start = Map("scene_one")

When I run this. 当我运行这个。 I don't get any output, but when I print directly from the class like this: 我没有任何输出,但是当我直接从此类打印时:

class FirstScene(object):
    print("printing scene 1")

It works. 有用。 Any suggestions? 有什么建议么?

You never call the enter() method of FirstScene object, this is why nothing is printed. 您永远不会调用FirstScene对象的enter()方法,这就是为什么什么都不打印的原因。

Change self.scene = scene by self.scene = Map.scenes[scene] to get the actual object, then call its enter method (but be warned that this method is not defined for SecondScene objects!). 通过self.scene = Map.scenes[scene]更改self.scene = scene以获取实际对象,然后调用其enter方法(但请注意,该方法未为SecondScene对象定义!)。

Another possibility is to rename enter of FirstScene to __init__ , so the print will be made upon instanciation. 另一种可能性是将FirstScene enter重命名为__init__ ,以便在实例化时进行打印。 In that case, you have to decide whether you want to instanciate your objects when defining Map.scenes as you're currently doing, or in the __init__ method of Map , eg, using self.scene = Map.scenes[scene]() . 在那种情况下,您必须决定在定义Map.scenes时是要实例化对象,还是在Map__init__方法中,例如使用self.scene = Map.scenes[scene]() In that case, you have to change the way you defined your dictionary on Map : 在这种情况下,您必须更改在Map上定义字典的方式:

scenes = {
    "scene_one": FirstScene,
    "scene_two": SecondScene,
}

A more elegant way to do it: 一种更优雅的方法:

class FirstScene(object):
    def __init__(self):
        print("printing scene 1")

class SecondScene(object):
    pass

class Map(object):
    def __init__(self, scene):
        self.scene = scene()

game_start = Map(FirstScene)

ie, you pass to the __init__ method of Map the class that has to be instanciated upon initialisation. 也就是说,您将必须在初始化时实例化的类传递给Map__init__方法。

__init__() is short for "initialize" and is the python way of dealing with something called Constructors in object oriented programming. __init__()是“初始化”的缩写,是在面向对象编程中处理称为“ 构造函数”的python方法。

I think it's best to use examples. 我认为最好使用示例。 Let's say you're creating a program called dog simulator. 假设您要创建一个称为“狗模拟器”的程序。

# Notice that animals are a CLASS of objects.
class Animal:
        # Before we do anything, we have to create an instance of an object.
        # If we want to do something to a file, we have to first create one, aka (initialize one)
        # __init__ means "initialize", the two underscores in pythong mean it's
        # a special function.
        def __init__(self):
                print("initializing a new animal...")

        # One thing that animals do is they eat. It's a "function" of animals.  
        def eat(self):
                print("mmmm... delicious")

# Notice that dogs are a CLASS of animals.
class Dog(Animal):
        # one function of a dog is we have to create a new instance of it
        def __init__(self):
                print("initializing a new dog...")
        # another function is that they bar.
        def bark(self):
                print("woof!")

# This is our main program. Notice it's checking if the name of
# this process is called "main".
if __name__ == "__main__":
        doggo = Dog() # Lets create a new dog, we'll name him doggo
        doggo.eat() # Since dogs are a "class" of animals, they can do everything animals do.
        doggo.bark() # They can also do dog specific stuff.

Here's a change to your code that prints: 这是您打印的代码的更改:

class FirstScene(object):
    def enter(self):
        print("printing scene 1")

class SecondScene(object):
    pass

class Map(object):

    scenes = {
        "scene_one": FirstScene(),
        "scene_two": SecondScene()
    }

    def __init__(self, scene):
        self.scene = self.scenes[scene]   ##### 1. Access the scene instance
        self.scene.enter()                ##### 2. Tell it to print

game_start = Map("scene_one")

In Map.__init__ , scene is the string "scene_one" At #1 above, you need to actually use the scenes dictionary that you created to get the FirstScene() or SecondScene() instance. Map.__init__scene是字符串"scene_one"在上述#1,你需要实际使用的scenes字典,创建获得FirstScene()SecondScene()实例。

Once you have an instance, at #2 above, you call the enter() method to cause whatever enter() does to happen. 有了实例后,在上面的#2中,您可以调用enter()方法使enter()发生任何事情。 In this case, that is printing printing scene 1 . 在这种情况下,即打印printing scene 1

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

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