简体   繁体   中英

Basic question about modules functions and classes

The following two code samples do the same thing. Am I interpreting how they work correctly?

How could I directly check if my interpretation is correct using python?

In code sample A the timeit module is imported and then the timeit function is used from the timeit module ( timeit.timeit ) - is this correct?

In code sample B t is an instance of the timer class, and the timer class is in the tiemit module. In code sample B, t.timeit() is using a timeit() method that's part of the timer class. The timeit() method used by t.timeit() is not the timeit function in code sample A ( timeit.timeit ), as the timeit method in code sample B is in the timer class, while in code sample A the timeit method is a function in the timeit module, and is not part of a class. Is this correct?

Code sample A:

import timeit
timeit.timeit('char in text', setup='text = "sample string"; char = "g"')

Code sample B:

import timeit
t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
t.timeit()

You can look into the source: https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/timeit.py#L229

Module level timeit is just a convenience wrapper.

Both of your codes will have the same effect, you can see this by running them, however the one you choose to execute will depend on your intention.

You can read more about this here: https://www.geeksforgeeks.org/difference-method-function-python/

This is also an excellent website for self taught programming and beginners.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM