在初始化中调用类/函数是正确的吗?

2024-04-16 10:45:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定这样做是否正确,但我有一个类,其中一些函数在另一个文件上使用同一个类。问题是,在init下调用一次类是否可以?如果我用一个使用查询/插入或http请求的类来做,会有什么复杂的情况?。或者我应该避免这样做?你知道吗

贝娄,我的意思的一个例子:

我的做法是:

类文件a.py

class StackExample:

    def __init__(self, input_a, input_b)
        self.var_a = input_a
        self.var_b = input_b

    def say_hello()
        print "My bacon is : " + self.var_a
        print "But still boss as : " + self.var_b

---

文件2.py

import classfileA

class Action:

    def __init__(self, input_a, input_b)
        self.var_a = input_a
        self.var_b = input_b    

    def test_a()
        start = classfileA.StackExample(self.var_a,self.var_b)
        start()

    def test_b()
        start = classfileA.StackExample(self.var_a,self.var_b)
        start()

    def test_c()
        start = classfileA.StackExample(self.var_a,self.var_b)
        start()

if __name__ == '__main__':
    run = action('my love','blind')
    run_cm.main()

我想我能做的是:

类文件a.py:

class StackExample:

    def __init__(self, input_a, input_b)
        self.var_a = input_a
        self.var_b = input_b

    def say_hello()
        print "My bacon is : " + self.var_a
        print "But still boss as : " + self.var_b

---

文件2.py

import classfileA

class Action:

    def __init__(self, input_a, input_b)
        self.var_a = input_a
        self.var_b = input_b
        # call inside __init__
        self.start = classFileA.StackExample(self.var_a,self.var_b)


    def test_a()        
        self.start()

    def test_b()
        self.start()

    def test_c()
        self.start()


if __name__ == '__main__':
    run = Action('my love','blind')
    run.test_a()

提前谢谢。你知道吗


Tags: 文件runpytestselfinputinitvar