I'm trying to do something I consider pretty ordinary in Object Oriented programming but can't find any documentation on it for Python 2.7 I want to create a subclass of a superclass where, when I'm done superclass is bound to the superclass superclass.subclass is bound to the subclass and subclass is bound to nothing. Here's the best solution I can come up with:
class superclass:
pass
class subclass(superclass):
pass
superclass.subclass = subclass
del subclass
Sometimes I want subclass to be in its own file, other times not. Is there a more elgant solution where I don't have to manually perform the last two lines? Although
class superclass:
class subclass:
pass
almost does the right thing, subclass doesn't actually inherit from superclass. And if I try to do:
class superclass:
class subclass(superclass):
pass
I get an error message that superclass is unbound.
2 Answers 2
I agree with everyone else that this is a silly thing to do and I don't think you should do it, but in the interest of knowledge:
class Superclass(object):
pass
Superclass.Subclass = type('Subclass', (Superclass,), {
'foo': lambda self: self,
})
where the dictionary argument contains any methods. I don't think there's a nice way to do this with the class syntax, but that's really just syntactic sugar for calling type anyway.
You don't have to define the methods as lambdas; they can be normal functions with def as long as they have the self argument. You'll probably want to hide their definitions if you do that, though....
1 Comment
Here's a simple class decorator to do the referencing:
def refer(cls):
cls.__bases__[0].subclass = cls
return cls
Here's how you use it:
>>> class Superclass:
pass
>>> @refer
class Subclass(SuperClass):
pass
You will still need to delete Subclass if you don't want the name in the module namespace.
1 Comment
setattr(cls.__bases__[0], cls.__name__, cls) to assign it to the name of the subclass; this would assign it as the literal name subclass, and so only works for one subclass.
superclassif you don't wantsubclassin your namespace.