python中一个py文件如何调用其他py文件中的类和函数

HelloWorld  文件名称  Hello是类

from HelloWorld import Hello

>>> h = Hello()

>>> h.hello()

Hello, world  # 输出结果

HelloWorld.py文件内容

class Hello(object):

  def hello(self, name='world'):

    print('Hellp, %s' %name)

在同一个文件下

调用函数:

A.py文件

def add(x, y):

  print ('和为: %d' %(x + y))

B.py文件

import A

A.add(1, 2)

或者

from A import add 

add(1, 2)

调用类:

A.py文件

class A:

  def __init__(self, xx, yy):

    self.x = xx

    self.y = yy

  def add (self):

    print ('x 和y的和为: %d' %(self.x + self.y))

B.py文件

from A import A

a = A(2, 3)

a.add()

或者

import A

a = A.A(2, 3)

a.add

在不同的文件夹下

A.py文件的文件路径: E:PythonProjectwinycg

B.py文件:

import sys

sys.path.append(r'E:PythonProjectwinycg')

"""python import 模块时, 是在sys.path里顺序查找的。

sys.path 是一个列表,里面以字符串的形式存储了许多路径。

使用A.py文件中的函数需要先将他的文件路径放到sys.path中

"""

import A

a = A.A(2, 3)

a.add()

import time 

import schedule

def search_train(train_number):

  print ("Train number: " + train_number)

schedule.every(10).seconds.do(search_train("23024")) 

while True:

  schedule.run_pending()

  time.sleep(1)

schedule.every(10).seconds.do(search_train("23024")) 这里写法是错误的,fix如下

schedule.every(10).seconds.do(search_train, "23024") 

原文地址:https://www.cnblogs.com/zcy1103/p/9697965.html