调用__init__中的类函数 [英] Calling a class function inside of __init__
问题描述
我写了一些代码,需要一个文件名,打开文件,并解析出一些数据。我想在一个类中这样做。以下代码适用于:
I'm writing some code that takes a filename, opens the file, and parses out some data. I'd like to do this in a class. The following code works:
class MyClass():
def __init__(self, filename):
self.filename = filename
self.stat1 = None
self.stat2 = None
self.stat3 = None
self.stat4 = None
self.stat5 = None
def parse_file():
#do some parsing
self.stat1 = result_from_parse1
self.stat2 = result_from_parse2
self.stat3 = result_from_parse3
self.stat4 = result_from_parse4
self.stat5 = result_from_parse5
parse_file()
但它涉及我把所有的解析机制放在我的类的 __ init __
函数的范围内。现在对于这个简化的代码看起来不错,但是函数 parse_file
也有相当数量的缩进。我更喜欢定义函数 parse_file()
作为类函数,如下所示:
But it involves me putting all of the parsing machinery in the scope of the __init__
function for my class. That looks fine now for this simplified code, but the function parse_file
has quite a few levels of indention as well. I'd prefer to define the function parse_file()
as a class function like below:
class MyClass():
def __init__(self, filename):
self.filename = filename
self.stat1 = None
self.stat2 = None
self.stat3 = None
self.stat4 = None
self.stat5 = None
parse_file()
def parse_file():
#do some parsing
self.stat1 = result_from_parse1
self.stat2 = result_from_parse2
self.stat3 = result_from_parse3
self.stat4 = result_from_parse4
self.stat5 = result_from_parse5
当然这个代码不工作,因为函数 parse_file ()
不在 __ init __
函数的作用域内。有没有办法从该类的 __ init __
中调用类函数?
Of course this code doesn't work because the function parse_file()
is not within the scope of the __init__
function. Is there a way to call a class function from within __init__
of that class? Or am I thinking about this the wrong way?
推荐答案
以这种方式调用函数:
self.parse_file()
你还需要像这样定义你的parse_file()函数:
You also need to define your parse_file() function like this:
def parse_file(self):
parse_file方法在调用它时必须绑定到一个对象上(因为它不是一个静态方法)。这是通过调用对象的实例上的函数来完成的,在你的情况下实例是 self
。
The parse_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self
.
这篇关于调用__init__中的类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!