Contiuing from this post: Dynamically creating a class from file, type(name, bases, dict) can be used to dynamically create a class with name name, with base classes bases, and attributes dict.
I have classes such as:
class City:
def __init__(self):
self.name = 0
class Building:
def __init__(self):
self.number = 100
I want to create a new class from a string (for ex. "School"), which inherits from the above classes. I have done:
School = type("School", (City, Building), {"school_name": "abc"}
s = School()
hasattr(s, "school_name") gives True. However, hasattr(s, "name") gives False.
How can I make sure that:
- My dynamically generated class
Schoolinherits the attributes of its base class(es)? - How can I add additional attributes to the class
Schoolafter already creating the classSchool = type("School", (Building, Home), {"school_name": "abc"}? (Suppose I want to add two new attributes (address,pincode) to the class later on in my script - can I do that?)
CityandBuildingbut your new type usesBuildingandHome... where's that come from?City.__init__andBuilding.__init__should be callingsuper().__init__. Neither actually defines any attributes, though. EvenCity().namewould raise an exception.typeexplicitly versus usingclass School(Building, Home): ...instead. (Your call totypedefines a class attribute namedschool_namewhenSchoolis defined.)dictdictionary argument. i.e. each key being a function name and the cooresponding value a functiondef.