如何获取python调用者对象信息?

时间:2012-10-21 12:10:31

标签: python introspection

如何从函数中获取调用者对象,并检查有关该调用者的信息?

class A(object):
    def class_A_fun(self):
            print 'caller from class'  # → B
            print 'caller from method'  # → class_B_fun
            print 'caller module'  # → foomodule
            print 'caller instance'  # → obj
            print 'caller object file name or path'  # → 'foomodule.py'

class B(object):
    def class_B_fun(self):    
        obj = A()
        obj.class_A_fun()        

if __name__ == "__main__":
    obj = B()
    obj.class_B_fun()

1 个答案:

答案 0 :(得分:1)

并非所有这些都是可能的,但大多数都是通过检查调用堆栈来获得的:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();

    String video = "android.resource://" + getPackageName() + "/" + R.raw.yakoob;
    String audio = "android.resource://" + getPackageName() + "/" + R.raw.ermia;

    try
    {
        H264TrackImpl mp4 = new H264TrackImpl(new FileDataSourceImpl(video));
        AACTrackImpl mp3 = new AACTrackImpl(new FileDataSourceImpl(audio));
        ////
        Movie movie = new Movie();
        movie.addTrack(mp4);
        movie.addTrack(mp3);
        Container con = new DefaultMp4Builder().build(movie);

        @SuppressWarnings("resource")
        FileChannel fc = new FileOutputStream(new File(baseDir+"/ramin.mp4")).getChannel();
        con.writeContainer(fc);
        fc.close();

    } catch (FileNotFoundException e) 
    {
        Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);  
        toast.show();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

有关详细信息,请参阅documentation for the inspect module