I've written some code that contains a main and a number of subclasses that inherit variables from a superclass.
E.g.
class superclass(object):
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
class subclass1(superclass):
def method1(self):
pass
class subclass2(superclass):
def method1(self):
pass
The main isn't shown, nor an option factory which is used to choose the subclass to call, but hopefully the info given will be sufficient.
I wish to convert those classes to standalone modules that can be imported. It is expected that additional subclasses will be written in the future so I was wondering if it is possible to save each subclass and the superclass as seperate modules and that the subclasses will still be able to use/have access too the superclass variables and definitions.
The reasoning behind this is to simplify the writing of any future subclasses. Meaning they can be written as a stand alone module and the previous subclasses and the superclass don't have to be touched as part of the development, but they will still be able to use the suberclasses variables and definitions.
I'm not sure how it would work or if it can be done that way. Whether I just save all the classes as superclass.py, subclass1.py and subclass2.py and import them all?????
Hope that made sense.
Thanks.
A subclass inherits everything from its superclass, which is referred to as inheritance in the object-orientation methodology and object-oriented programming. By inheritance, the superclass's attributes will not repeat in any of its subclasses.
The process of creating a subclass of a class is called inheritance. All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass.
In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass. Below is a sample Python program to show how inheritance is implemented in Python. # Base or Super class.
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ). It typically creates its underlying data structure.
Yes, its totally possible. Just don't forget to import superclass in the subclass file:
from module_where_superclass_is import SuperClass
class SubClass(SuperClass):
def method1(self):
# ...
Yes, obviously that is possible - That is the beauty of python !
Module 1
class base:
def p(self):
print "Hello Base"
Module 2
from module1 import base
class subclass(base):
def pp(self):
print "Hello child"
Python Shell
from module2 import subclass
ob = subclass()
ob.p()
"Hello Base"
ob.pp()
"Hello child"
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With