-3

I want to get a list of classes in my class. According to this answer How to find all the subclasses of a class given its name? I should be able to use cls.__subclasses__, but this function does not exist.

I tried the answer to question How to find all the subclasses of a class given its name?

class X:
  class my_subclass:
    pass

x=X()
x.__subclassess__()

# This reports AttributeError 'X' has no attribute '__subclasses__'

I would expect to get a dictionary object or the like. But I just get an error message AttributeError 'X' has no attribute '__subclasses__'.

martineau
  • 119,623
  • 25
  • 170
  • 301
Roger
  • 1
  • 1
  • 3
    That's not what a subclass is, by the way. – user2357112 May 31 '19 at 00:00
  • The name of the function is [`__subclasses__()`](https://docs.python.org/3/library/stdtypes.html#class.__subclasses__) and it's a `class` method, not an instance method, so you would need to use `type(x).__subclasses__()`. However the list returned will be empty because `my_subclass` is a class _nested_ inside `X`, not a subclass of it. – martineau May 31 '19 at 01:57

2 Answers2

3

You're doing 3 things wrong.

1) That's not how you make a subclass.

A subclass is not a class inside a class, rather it's a separate class that you define that inherits from a parent/base class. See Python: How do I make a subclass from a superclass?

class Cake():
    pass

# a subclass of Cake
class Crepe(Cake):
    pass

# a subclass of Cake
class Pound(Cake):
    pass

2) You have to call __subclasses__ on the parent class name, not on the instance.

an_instance_of_crepe=Crepe()

an_instance_of_crepe.__subclasses__()
# This will result in "AttributeError: 'Crepe' object has no attribute '__subclasses__'"
# This is what you are getting

Cake.__subclasses__()
# This will work, and printing out the result will give
# [<class '__main__.Crepe'>, <class '__main__.Pound'>]

3) It's __subclasses__ (1 's' at the end)

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
0

The name of the method is

__subclasses__

You wrote:

__subclassess__

See the extra 's'?

jwodder
  • 54,758
  • 12
  • 108
  • 124