Python 我已经编写了两个独立的文件,一个包含类,另一个调用它们,但调用一个使所有对象都成为对象。为什么?
分开Python 我已经编写了两个独立的文件,一个包含类,另一个调用它们,但调用一个使所有对象都成为对象。为什么?,python,python-2.7,Python,Python 2.7,分开 class foo(): print 'a bunch of time consuming work' class tryme(): print 'try me'* main.py from separate import * foo() 然而,它同时印刷了以下两种文字: a bunch of time consuming work try me 你应该为你的类写一个init,这样它就不会再发生了 class foo(): def
class foo():
print 'a bunch of time consuming work'
class tryme():
print 'try me'*
main.py
from separate import *
foo()
然而,它同时印刷了以下两种文字:
a bunch of time consuming work
try me
你应该为你的类写一个init,这样它就不会再发生了
class foo():
def __init__(self):
print('a bunch of time consuming work')
class tryme():
def __init__(self):
print ('try me')
从单独导入调用
时*
执行打印命令!
如果您只想创建一个实例,请执行以下操作:
class foo():
def my_print(self):
print 'a bunch of time consuming work'
从main调用我的指纹
f = foo()
f.my_print
由于类范围内的命令是静态定义的,因此在导入模块时,它也会在绑定所有内容时启动静态字段。
@Tino A为您提供了一个很好的解决方案,但是如果您想阅读更多关于python中导入的资料,请尝试。只是一个提示:您应该像函数一样使用print(print(“…”)来准备python 3。