简体   繁体   English

我可以包括保存在另一个文件中的类方法的Python实现吗

[英]Can I include Python implementation of class method saved in another file

In Python, we cannot save class method's definition outside of class definition itself (as I understand it) because there is no concept of declaration. 在Python中,因为没有声明的概念,所以无法将类方法的定义保存在类定义本身之外(据我所知)。 However, I wonder whether it is possible that I can include source code of method implementation saved in a standalone file, namely having the interpreter replace the piece of code in question. 但是,我不知道我是否可以包含保存在独立文件中的方法实现的源代码,即让解释器替换所讨论的代码段。 But as I have never seen such thing, this is probably not idiomatic in Python. 但是,正如我从未见过的那样,这在Python中可能不是惯用语言。 Then how do you deal with the irritation that a class definition will be extremely long? 那么您如何处理类定义将非常长的烦恼呢? Please correct me since I am new to Python, and find it quite different from C++. 由于我是Python的新手,请纠正我,并发现它与C ++完全不同。

class Foo
   def bar():
      # How to include definition saved in another file?
import another_file

class Foo
   def bar():
      another_file.class_name/def_name ...

or import just particular definition 或仅导入特定定义

from another_file import def_name

class Foo
   def bar():
      def_name ...

Can do! 可以做!

First solution 第一个解决方案

bar.py bar.py

def bar(foo):
    print foo

foo.py foo.py

from bar import bar as foo_bar

class Foo:
    bar = foo_bar

Alternative solution 替代解决方案

bar.py bar.py

def bar(foo):
    print foo

foo.py foo.py

from bar import bar as foo_bar

class Foo:
    def bar(self, *args, **kwargs):
        return foo_bar(self, *args, **kwargs)

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

相关问题 如何在python中另一个文件下的另一个类中调用一个方法? - How can I call a method which is in another class under another file in python? 在 python 中的另一个文件中包含类中的函数 - Include functions in class from another file in python 如何从 Python 中的另一个文件调用类方法? - How do I call a class method from another file in Python? 我可以将Python SocketServer类用于此实现吗? - Can I use the Python SocketServer class for this implementation? 如何从另一个文件(在另一个文件夹中)包含 class - python - How to include class from another file(in another folder) - python 在 Python 中,如何在不更改命名空间的情况下将一个文件包含(不导入)到另一个文件中,宏样式? - In Python, how can I include (not import) one file within another file, macro style, without changing namespace? 如何从 python 中的另一个文件导入 class? - How can i import class from another file in python? Python - 我可以从另一个文件导入变量作为类变量吗? - Python - Can I import variables from another file as class variables? 我可以将python变量存储在另一个文件中的类中吗? - Can I store python variables inside a class in another file? 方法链接时如何在python类方法中返回self和另一个变量? - How can I return self and another variable in a python class method while method chaining?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM