python调用其他文件中的函数或者类

01 在同一个文件夹下,调用函数或者类

A.py文件中

def test():
	print('this is test func')

class A:
    def test():
        print('this is a class named A, its func is test() ')

B.py文件中

# way 1
from A import test
from A import A

test()

a = A()
a.test()

# way 2
import A
A.test()
a = A.A()
a.test()
02 在不同文件夹下,调用函数或者类

src文件夹与B.py文件在同一目录下,src文件夹下有C.py文件

C.py文件中

def test():
	print('this is test func')

class C:
    def test(self):
        print('this is a class named C, its func is test() ')
        

B.py文件中

from src.C import test
from src.C import C

test()

a = C()
a.test()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python调用其他文件函数可以使用以下几种方式: 1. 使用import语句:在Python,可以使用import语句导入其他模块(文件),并使用其定义的函数。例如,如果在一个名为`other_module.py`的文件定义了一个名为`add_numbers`的函数,我们可以使用以下方式在另一个文件调用函数: ```python from other_module import add_numbers result = add_numbers(3, 5) print(result) ``` 在上面的例子,我们从`other_module`模块导入了`add_numbers`函数,并在当前文件调用它。这种方法适用于其他函数和变量的导入。 2. 使用exec()函数:如果需要在运行时动态地调用其他文件函数,可以使用Python内置的exec()函数。例如,假设我们有一个名为`other_file.py`的文件,其定义了一个名为`my_function`的函数,我们可以使用以下方式在当前文件调用它: ```python # 执行包含my_function的文件 exec(open('other_file.py').read()) # 调用my_function函数 result = my_function(3, 5) print(result) ``` 在上面的例子,我们使用exec()函数执行了`other_file.py`文件的代码,并在当前文件调用了`my_function`函数。需要注意的是,使用exec()函数执行其他文件的代码存在一定的安全风险,因此建议仅在必要时使用。 希望这些例子能够帮助您理解如何在Python调用其他文件函数。如果您有其他问题或需要更多帮助,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值