0

I want to perform the following scala code into python3 language

    class xyz{  
      def abc():Unit={  
        val clazz:Class[_] = this.getClass()
        var fields: List[String] = getFields(clazz);
        val method = clazz.getDeclaredMethods()
        val methodname=method.getName()
        val supper= clazz.getSuperclass()
        println(clazz)
        println(fields)
        println(method)
}}
creatorworld
  • 21
  • 1
  • 6

2 Answers2

3

Class[_] equivalent in python

Class[_] is a static type. Python doesn't have static types, so there is no equivalent to the static type Class[_] in Python.

I want to perform the following scala code into python3 language

class xyz{  
 def abc():Unit={  
   val clazz:Class[_] = this.getClass()
   var fields: List[String] = getFields(clazz);
   val method = clazz.getDeclaredMethods()
   val methodname=method.getName()
   val supper= clazz.getSuperclass();}
 def mno():Unit={
   println("hello")}}

abc is simply a NO-OP(*). mno just prints to stdout. So, the equivalent in Python is

class xyz:
  def abc(self):
    pass

  def mno(self):
    print("hello")

Note that I made abc and mno instance methods, even though it makes no sense. (But that's the same for the Scala version.)


(*) Some who knows more about corner cases and side-effects of Java Reflection can correct me here. Maybe, this triggers some kind of Classloader refresh or something like that?

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • please see the post again .........I have done some editing. whatever value is returned by the methods used like getClass(), getFields() etc ......I want same kind of value using python – creatorworld May 27 '20 at 13:55
2

You can't get one-to-one correspondence simply because Python classes are organized very differently from JVM classes.

  1. The equivalent of getClass() is type;

  2. there is no equivalent to Class#getFields because fields aren't necessarily defined on a class in Python, but see How to list all fields of a class (and no methods)?.

  3. Similarly getSuperclass(); Python classes can have more than one superclass, so __bases__ returns a tuple of base classes instead of just one.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Also, there is no equivalent to `getDeclaredMethods` because methods are actually just (well, not quite, but close enough) functions assigned to fields (see #2). And there is no equivalent to `getName` because methods (functions) don't have names, they are simply objects assigned to variables / fields (see #2 again). – Jörg W Mittag May 27 '20 at 14:51