首页 > 解决方案 > 有人可以帮我写日志 - 错误:绑定方法吗?

问题描述

任何帮助表示赞赏。我能够让它打印到日志中,但我收到了绑定方法错误。我认为这与我的异常处理中的 + str 有关。

else:
     Leibniz_object = MarshallHomework6.Pi_LeibnizClass(10)
     logging.basicConfig(filename='example.log',
                         format='%(asctime)s %(levelname)s: %(message)s',
                         level=logging.INFO)
                msg1 = 'The circumference of circle is: ' + str(Leibniz_object.get_circumference)()
                logging.info(msg1)
                msg2 = 'The area of a circle is: ' + str(Leibniz_object.get_area)()
                logging.info(msg2)
                msg3 = 'The volume of a circle is: ' + str(Leibniz_object.get_volume)()
                logging.info(msg3)
                msg4 = 'The surface area of a circle is: ' + str(Leibniz_object.get_surfacearea)()
                logging.info(msg4)
                ending()

标签: python

解决方案


没有看到MarshallHomework6.Pi_LeibnizClass类的代码很难确定,但在这样的陈述中......

msg1 = 'The circumference of circle is: ' + str(Leibniz_object.get_circumference)()

...看起来你放错了一组括号。要调用函数或方法,请编写object.methodname(). 如果你省略了括号,或者它们没有紧跟在函数名后面,那么你就没有调用函数。您获得的不是函数返回值,而是对函数本身的引用(当您将其转换为字符串时,会产生类似 的内容<bound method Pi_LeibnizClass.get_volume of <__main__.Pi_LeibnizClass object at 0x7f0cd85cde50)。对此有有效的用例,但这可能不是您想要的。

我想你的意思是写:

msg1 = 'The circumference of circle is: ' + str(Leibniz_object.get_circumference())

同样:

msg2 = 'The area of a circle is: ' + str(Leibniz_object.get_area())
msg3 = 'The volume of a circle is: ' + str(Leibniz_object.get_volume())
msg4 = 'The surface area of a circle is: ' + str(Leibniz_object.get_surfacearea())

这是我用来测试的代码(使用虚拟类,因为我不知道MarshallHomework6模块是什么样的):

import logging

class Pi_LeibnizClass:
    def __init__(self, val):
        self.val = val

    def get_circumference(self):
        return 1

    def get_area(self):
        return 2

    def get_volume(self):
        return 3

    def get_surfacearea(self):
        return 4


Leibniz_object = Pi_LeibnizClass(10)
logging.basicConfig(
        format='%(asctime)s %(levelname)s: %(message)s',
        level=logging.INFO)
msg1 = 'The circumference of circle is: ' + str(Leibniz_object.get_circumference())
logging.info(msg1)
msg2 = 'The area of a circle is: ' + str(Leibniz_object.get_area())
logging.info(msg2)
msg3 = 'The volume of a circle is: ' + str(Leibniz_object.get_volume())
logging.info(msg3)
msg4 = 'The surface area of a circle is: ' + str(Leibniz_object.get_surfacearea())
logging.info(msg4)

这输出:

2021-07-23 16:59:47,379 INFO: The circumference of circle is: 1
2021-07-23 16:59:47,379 INFO: The area of a circle is: 2
2021-07-23 16:59:47,379 INFO: The volume of a circle is: 3
2021-07-23 16:59:47,379 INFO: The surface area of a circle is: 4

推荐阅读