Python 名称错误:名称';脚本的开始时间&x27;没有定义

Python 名称错误:名称';脚本的开始时间&x27;没有定义,python,function,Python,Function,我知道我在使用python函数时犯了一些基本错误。你介意分享一个解决方案吗。谢谢。您可以将以后要检索的值分配给self。如下所示: import time import datetime class TimeCounter(): def startTime(): start_time_of_the_script = time.time() def endTime(): end_time_of_the_script = time.time(

我知道我在使用python函数时犯了一些基本错误。你介意分享一个解决方案吗。谢谢。

您可以将以后要检索的值分配给
self。
如下所示:

import time
import datetime

class TimeCounter():

    def startTime():

        start_time_of_the_script = time.time()

    def endTime():

        end_time_of_the_script = time.time()
        process_time_in_seconds = end_time_of_the_script - 
start_time_of_the_script
        print(str(datetime.timedelta(seconds=process_time_in_seconds)))

def main():

    TimeCounter.startTime()
    TimeCounter.endTime()

main()

您需要区分类和实例。将
TimeCounter
定义为类后,可以创建一个或多个实例。这在下面的赋值
tc=TimeCounter()
中完成,该赋值创建
TimeCounter
的新实例,并将其赋值给变量
tc

在类的实例上调用方法(函数)时,实例作为参数传递给方法,传统上称为self。因此,当下面的代码调用
tc.startTime()
时,
startTime
中的
self
参数将引用
tc
实例。另外,当
startTime
设置脚本的
self.start\u时间时,它正在创建
tc
实例的新属性,然后在
endTime
中再次读取该属性

import time
import datetime

class TimeCounter:

   def startTime(self):

        self.start_time_of_the_script = time.time()

    def endTime(self):

        self.end_time_of_the_script = time.time()
        self.process_time_in_seconds = self.end_time_of_the_script - self.start_time_of_the_script
        print(str(datetime.timedelta(seconds=self.process_time_in_seconds)))

谢谢它确实有用!但另一个问题是,;为什么我们也不写self.end\u time\u of theu脚本:end\u time\u of theu脚本和self.process\u time\u in \u秒:process\u time\u in \u秒。为什么在我们没有错误的情况下它不会给出任何错误在上面的示例中,我们没有在类TimeCounter()中编写对象:创建TimeCounter类时,代码确实起了作用。我想知道在什么情况下我们必须在类paranthesis中写入对象?@questioneer1“是”括号用于一个类对另一个类进行子类化。这里似乎没有必要。我引用了这篇文章:。看来我们在这里都学到了一些东西。我将从我的答案中删除这一点。这里还有一个链接进一步解释了这一点:是的,我也学到了非常重要的东西。如果我想稍后从pythonshell或其他函数调用例如:process_time_in_seconds,该怎么办?因为它不像我在类中使用函数时在shell中以秒为单位编写process\u time\u那样简单。在实例化之后,您可以从类的实例中检索类属性。因此,如果您的类实例是
tc
,您可以使用
tc.process\u time\u以秒为单位检索所述值。
import time
import datetime

class TimeCounter:  # Parentheses not necessary

    def startTime(self):  # Note self parameter

        self.start_time_of_the_script = time.time()  # Set a property of the instance

    def endTime(self):  # Note self parameter

        end_time_of_the_script = time.time()  # This is a local variable
        process_time_in_seconds = end_time_of_the_script - self.start_time_of_the_script
        print(datetime.timedelta(seconds=process_time_in_seconds))

def main():

    tc = TimeCounter()  # Create a fresh instance of TimeCounter and assign to tc
    tc.startTime()  # Call method startTime on the tc instance
    tc.endTime()

main()