creatorworld
creatorworld

Reputation: 21

Class[_] equivalent 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()
        println(clazz)
        println(fields)
        println(method)
}}

Upvotes: 0

Views: 93

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170859

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.

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369594

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?

Upvotes: 3

Related Questions