如何将Python函数移动到不同的.py文件?
我想把很多文件里的函数移动到单独的 Python 文件里去。可是如果我这么做,就不行了。
我试过:
文件:server.py:
import os, cherrypy, json
from customers.py import *
class application(object):
def get_webpage(self):
....
def get_data(self):
....
文件:customers.py:
import os, cherrypy, json
def get_customer_data(self):
....
我把 Python 当作服务器来用,函数 get_customer_data 里的数据在这种情况下没有被处理,结果是 404 找不到,意思是这个函数没有在主文件(server.py)里包含进来。
1 个回答
1
我把get_webpages()里的self去掉了,因为它没有缩进,这意味着它不是这个类的一部分。
application.py:
class application(object):
def __init__(self):
pass
def get_webpage():
print('From application')
customers.py:
from application import *
get_webpage() # From application
你可以把get_webpages()缩进,这样它就成了这个类的一部分。这样调用它的方式会有所不同。(我把self加回去了,并且把类的名字首字母大写了。)
application.py:
class Application(object):
def __init__(self):
pass
def get_webpage(self):
print('From application')
customers.py:
from application import *
a = Application()
a.get_webpage() # From application