【问题标题】:How do I pass in a self argument to python cProfile如何将 self 参数传递给 python cProfile
【发布时间】:2020-07-15 16:51:31
【问题描述】:

我正在尝试将 cProfiling 与 python 一起使用。

我的python项目的目录结构如下:

my-project
├── src
│   ├── lib 
│       └── app
│           └── data
│               └── car_sim.py
│
│
│
│
├── ptests 
│   ├── src 
│       └── lib 
│           └── app
│               └── data
│                   └── cprofile_test.py

我在 car_sim.py 中有一个我想要 cprofile 的函数,它被称为“sim_text”。它包含一个名为:

#car_sim.py
import os

class RootSimulator:

    def sim_text(self, text):
            return text

我在 cprofile_test.py 中使用以下代码:

#cprofile_test.py
import cProfile
import pstats
import io

import src.lib.app.data.car_sim as car_sim_functions


pr = cProfile.Profile()
pr.enable()
text = 'my blabla sentence' #i can pass in this text below i guess...

#how do i pass to the below????!!
my_result = car_sim_functions.RootSimulator.sim_text()

pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()

with open('test.txt', 'w+') as f:
    f.write(s.getvalue())

现在...当我使用命令运行它时

python -m cProfile ptests/src/lib/app/data/cprofile_test.py

我收到以下错误:

TypeError: sim_text() 缺少 2 个必需的位置参数:'self' 和 'text'

我的问题是......它需要 2 个参数,那么我如何传递“自我”参数。对于第二个参数,“文本”我可以传入一个值没问题。

【问题讨论】:

    标签: python performance-testing cprofile


    【解决方案1】:
    class RootSimulator:
    
        def sim_text(self, text):
                return text
    

    RootSimulator 的实例上定义一个实例方法。您正在尝试从课程本身调用sim_text。你需要创建一个实例:

    simulator = car_sim_functions.RootSimulator()
    my_result = simulator.sim_text()
    

    如果sim_text()实际上不需要附加到模拟器的实例上,也许你根本不需要一个类(只要把它变成一个普通函数),或者你可以把它变成一个静态方法:

    class RootSimulator:
    
        @staticmethod
        def sim_text(text):
                return text
    

    请注意,它不再需要self

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 2017-12-29
      • 1970-01-01
      • 2016-04-27
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      相关资源
      最近更新 更多