【问题标题】:How to call a class method in another method in python?如何在python的另一个方法中调用一个类方法?
【发布时间】:2013-01-18 03:09:29
【问题描述】:

我正在尝试打印“好的,谢谢”。当我在 shell 上运行它时,它会在单独的行上打印,并且“谢谢”在“好的”之前打印。谁能帮助我做错了什么?

>>> test1 = Two() 
>>> test1.b('abcd') 
>>> thanks 
>>> okay

我的代码

class One:
     def a(self):
         print('thanks')

class Two:
     def b(self, test):
         test = One()
         print('okay', end = test.a())

【问题讨论】:

    标签: python class methods


    【解决方案1】:

    您的问题是,当您调用test.a() 时,您会打印一个字符串,而不是返回它。更改您的代码执行此操作,它会正常工作:

     def a(self):
         return 'thanks'
    

    根据您在问题中所说的,您似乎不需要对print 使用end 关键字参数。只需将 test.a() 作为另一个参数传递:

    print('okay,', test.a())
    

    【讨论】:

      【解决方案2】:

      print 在处理结果表达式之前按顺序计算函数。

      def a(): print('a')
      def b(): print('b')
      def c(): print('c')
      
      print(a(), b())
      print('a', b())
      print ('a', b(), c())
      print (a(), 'b', c())
      

      输出:

      a
      b
      (None, None)
      b
      ('a', None)
      b
      c
      ('a', None, None)
      a
      c
      (None, 'b', None)
      

      因此,python 在将元组传递给打印之前对其进行评估。在评估它时,方法 'a' 被调用,导致打印 'thanks'。

      然后b 中的 print 语句继续进行,这将导致打印 'okay'。

      【讨论】:

        【解决方案3】:

        要打印“好的,谢谢”,您的 One.a() 应该返回一个字符串而不是单独的打印语句。

        也不确定 Two.b 中的“test”参数是什么,因为您立即将其覆盖为 One 类的实例。

        class One:
            def a(self):
                return ' thanks'
        
        class Two:
            def b(self):
                test = One()
                print('okay', end = test.a())
        
        >>>> test1 = Two()
        >>>> test1.b()
        okay thanks
        >>>>
        

        【讨论】:

          【解决方案4】:

          我会尝试这样的事情,因为这意味着您不必更改一级。这减少了您必须更改的类的数量,从而隔离了更改和错误范围;并保持第一类的行为

          class One:
               def a(self):
                   print('thanks')
          
          class Two:
               def b(self, test):
                   test = One()
                   print('okay', end=' ')
                   test.a()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-11-07
            • 1970-01-01
            • 2019-05-22
            • 2017-07-16
            • 2021-08-28
            • 1970-01-01
            • 2011-01-15
            相关资源
            最近更新 更多