[英]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! 可以做!
def bar(foo):
print foo
from bar import bar as foo_bar
class Foo:
bar = foo_bar
def bar(foo):
print foo
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.