简体   繁体   English

如何跨类重用函数

[英]How can I reuse functions across classes

I have a few functions I'd like to reuse. 我有一些我想重用的功能。 This isn't my EXACT example but it is functionally similar. 这不是我的EXACT示例,但功能相似。

For example, we'll say I have a bunch of python lists of integers that live in different classes that are each their own file. 例如,我们将说我有一堆整数的python列表,这些列表位于不同的类中,每个类都是自己的文件。 ListClassA.py, ListClassB.py, ListClassC.py. ListClassA.py,ListClassB.py,ListClassC.py。

I want to get averages for all those classes. 我想获得所有这些课程的平均值。 I could make a nice little function in every single class that says sum the list and divide it by the length. 我可以在每个类中做一个不错的小功能,说出列表的总和并除以长度。 What I'd like to do is make a new class that can do all my nice little list functions (average, max value, etc) so I can just call listFunctions.average(list). 我想做的是创建一个新类,该类可以执行我所有漂亮的小列表函数(平均值,最大值等),因此我可以仅调用listFunctions.average(list)。 How can I call my new class from my existing classes? 如何从现有班级中调用新班级?

You can import the new class 您可以import新类

from new_file import listFunctions

Then you can use listFunctions.average(list) 然后可以使用listFunctions.average(list)

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

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