简体   繁体   English

导入的模块打印出无

[英]Imported module prints out None

I am not sure if anyone asked this already but I could not find was I was looking for, so here we go. 我不确定是否有人已经问过这个问题,但是我找不到我要找的东西,所以我们开始吧。 I have created a module named xxx.py. 我创建了一个名为xxx.py的模块。 This is whats inside: 这是里面的东西:

class A(object):
     def aaa(self):
        print "Ahaaaa!!!!!!!!!!!!!!!"

Also I have another script ex45.py: 另外我还有另一个脚本ex45.py:

from xxx import A

xxx = A()
print xxx.aaa()

When I run python ex45.py I get the following: 当我运行python ex45.py时,我得到以下信息:

PS E:\python\ex\ex45> python ex45.py
Ahaaaa!!!!!!!!!!!!!!!
None

Why is there that 'None'??? 为什么会出现“ None” ???

My purpouse is to write multipe scripts where I create classes that I want to use in another script. 我的目的是编写multipe脚本,在其中创建要在另一个脚本中使用的类。 I am sure there are better ways to code but I am now learning python and I want to understand how everything works. 我确信有更好的编码方法,但是我现在正在学习python,我想了解一切工作原理。

PS: I am using python 2.7.9. PS:我正在使用python 2.7.9。 and learning from the book Learn Python the hard way. 并从这本书中学习“学习Python”。

It's because your aaa() method returns None . 这是因为您的aaa()方法返回None Sou you print out something and then you also print out the returned value. 例如,您先打印出一些内容,然后还打印出返回值。 Try this: 尝试这个:

from xxx import A

xxx = A()
xxx.aaa()

And this (one at time): 这(一次一个):

class A(object):
     def aaa(self):
         return "Ahaaaa!!!!!!!!!!!!!!!"

And see what happens. 看看会发生什么。

The aaa method prints out "Ahaaaa!!!!!!!!!!!!!!!" aaa方法将输出"Ahaaaa!!!!!!!!!!!!!!!" and returns nothing (in Python what doesn't return anything actually returns None ). 并且不返回任何内容(在Python中什么都不返回实际上返回None )。 Then, in ex45.py you print the return value of aaa , which is None . 然后,在ex45.py ,打印aaa的返回值,即None

To solve the problem, you may either do xxx.aaa() (without print ing), or in the aaa method return "Ahaaaa!!!!!!!!!!!!!!!" 要解决该问题,您可以执行xxx.aaa() (不print ),或者在aaa方法中返回"Ahaaaa!!!!!!!!!!!!!!!" instead of print ing it. 而不是print它。

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

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