You probably want something like a Coin class for penny, nickel, dime, quarter to inherit from. Also you should only have one init method

class Coin():
    def __init__(self,weight,height):
        self.weight = weight
        self.height = height

class Penny(Coin):
    def __init__(self):
        Coin.__init__(self,2.5,1.52)
Answer from Jack burridge on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes
Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. ... Note: Each object is independent and has its own copy of the class properties. class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.8 documentation
5 days ago - Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this: class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment.
Discussions

How to create a Python class - Stack Overflow
Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content. Stack Ads Connect your brand to the world’s most trusted technologist communities. Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create ... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I dynamically create derived classes from a base class - Stack Overflow
Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content. Stack Ads Connect your brand to the world’s most trusted technologist communities. Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create ... More on stackoverflow.com
🌐 stackoverflow.com
Understanding classes, init and self
Could you explain this code excerpt? I am learning and trying to get in touch with the logic of classes · The __init__ method initialises a new instance (object) of the class NewWindow. The actual creation of the instance is done by a separate method __new__, before __init__ is called. More on discuss.python.org
🌐 discuss.python.org
19
0
February 16, 2024
Python Class tutorial
Hi there i have completed a an exercise from a book and wanted you guys to have a look, I think its giving me back the results needed but i cant tell for sure if i have answered the questions rightly and the code i wrote is not error prone. better coding suggestions are welcome: “”" User ... More on discuss.python.org
🌐 discuss.python.org
3
0
April 30, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
It is shared across all instances of Dog class, so can be directly accessed through instance dog1. __init__() method acts as a constructor and is automatically executed when an object is created. It is used to initialize the attributes of the object with the values provided at the time of object creation.
Published: 2 weeks ago
🌐
Mimo
mimo.org › glossary › python › class
Mimo: The coding platform you need to learn Web Development, Python, and more.
A class in Python is a blueprint for creating objects. An object is an instance of a class, with its own unique attributes and methods. You define a class using the class keyword and initialize its attributes with the special __init__() method.
🌐
Martin Fitzpatrick
martinfitzpatrick.com › tutorials › working with classes in python
Working With Classes in Python
March 6, 2023 - In this example, we defined our Color class using the class keyword. This class is empty. It doesn't have attributes or methods. Its body only contains a pass statement, which is Python's way to do nothing. Even though the class is minimal, it allows us to create instances by calling its constructor, Colo().
Find elsewhere
Top answer
1 of 5
194

This bit of code allows you to create new classes with dynamic names and parameter names. The parameter verification in __init__ just does not allow unknown parameters, if you need other verifications, like type, or that they are mandatory, just add the logic there:

class BaseClass(object):
    def __init__(self, classtype):
        self._type = classtype

def ClassFactory(name, argnames, BaseClass=BaseClass):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            # here, the argnames variable is the one passed to the
            # ClassFactory call
            if key not in argnames:
                raise TypeError("Argument %s not valid for %s" 
                    % (key, self.__class__.__name__))
            setattr(self, key, value)
        BaseClass.__init__(self, name[:-len("Class")])
    newclass = type(name, (BaseClass,),{"__init__": __init__})
    return newclass

And this works like this, for example:

>>> SpecialClass = ClassFactory("SpecialClass", "a b c".split())
>>> s = SpecialClass(a=2)
>>> s.a
2
>>> s2 = SpecialClass(d=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __init__
TypeError: Argument d not valid for SpecialClass

I see you are asking for inserting the dynamic names in the naming scope -- now, that is not considered a good practice in Python - you either have variable names, known at coding time, or data - and names learned in runtime are more "data" than "variables" -

So, you could just add your classes to a dictionary and use them from there:

name = "SpecialClass"
classes = {}
classes[name] = ClassFactory(name, params)
instance = classesname

And if your design absolutely needs the names to come in scope, just do the same, but use the dictionary returned by the globals() call instead of an arbitrary dictionary:

name = "SpecialClass"
globals()[name] = ClassFactory(name, params)
instance = SpecialClass(...)

(It indeed would be possible for the class factory function to insert the name dynamically on the global scope of the caller - but that is even worse practice, and is not compatible across Python implementations. The way to do that would be to get the caller's execution frame, through sys._getframe(1) and setting the class name in the frame's global dictionary in its f_globals attribute).

update, tl;dr: This answer had become popular, still its very specific to the question body. The general answer on how to "dynamically create derived classes from a base class" in Python is a simple call to type passing the new class name, a tuple with the baseclass(es) and the __dict__ body for the new class -like this:

>>> new_class = type("NewClassName", (BaseClass,), {"new_method": lambda self: ...})

update
Anyone needing this should also check the dill project - it claims to be able to pickle and unpickle classes just like pickle does to ordinary objects, and had lived to it in some of my tests.

2 of 5
130

type() is the function that creates classes and in particular sub-classes, like in the question:

def set_x(self, value):
    self.x = value

# type() takes as argument the new class name, its base
# classes, and its attributes:
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x})
# (More methods can be put in SubClass, including __init__().)

obj = SubClass()
obj.set_x(42)
print obj.x  # Prints 42
print isinstance(obj, BaseClass)  # True
🌐
YouTube
youtube.com › watch
Python Tutorial - Introduction to Classes
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new featuresNFL Sunday Ticket
🌐
YouTube
youtube.com › watch
Learn Python • #11 Classes • Create and Use Classes in Python - YouTube
Classes are like a blueprint for creating your own reusable data structures in Python. They allow you to define your own custom data types, with properties a...
Published: April 6, 2023
🌐
OpenClassrooms
openclassrooms.com › us › courses › 6900856-learn-programming-with-python › 6993022-write-a-python-class
Write a Python Class - OpenClassrooms
You can find the solution to this exercise in this GitHub repository. Make a class using the class keyword. The __init__ method is known as the constructor. Constructors are called when an object is created.
🌐
Pybites
pybit.es › articles › python-classes
How to Write a Python Class – Pybites
A Pig will always have a set amount of health to begin with, you’re just specifying how much it gets when you create it. I wrote a basic Person Class this week for our 100 Days of Code Challenge. I’ll break it down for you to make this easier. The code for this example is here. A person is as simple as it gets. We’re all people but we differ immensely. We’re different ages, different heights, weights, sexes, colours and so on. At the end of the day, we’re still people – which makes us a great Class use case! ... class Person(object): def __init__(self, name, age, height, weight, gender, job): self.name = name self.age = age self.height = height self.weight = weight self.gender = gender self.job = job
🌐
Real Python
realpython.com › python-classes
Python Classes: The Power of Object-Oriented Programming – Real Python
August 2, 2026 - To create an object of a Python class like Circle, you must call the Circle() class constructor with a pair of parentheses and a set of appropriate arguments. What arguments? In Python, the class constructor accepts the same arguments as the .__init__() method.
🌐
Quora
quora.com › How-do-you-create-a-private-class-in-Python
How to create a private class in Python - Quora
Answer: In python there is no formal private keyword, instead it is achieved through the naming convention. Typically, local variable has a naming convention of a single underscore carries and has a local variable convention meaning. Double pre underscore is used for name mangling of the subclass...
🌐
Reddit
reddit.com › r › learnpython › comments › 1162yka › creating_classes
Creating classes : r/learnpython
After looking at various options, I found Python and how it's useful in many places. My tech skills are absolutely basic, I mean I can navigate stuff and if I don't know anything I can look up how to go about it but coding and creating stuff is beyond me.
🌐
Python documentation
docs.python.org › 3 › reference › datamodel.html
3. Data model — Python 3.14.8 documentation
Custom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes).
🌐
pytest
docs.pytest.org › en › stable › getting-started.html
Get Started - pytest documentation
Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test: # content of test_class.py class TestClass: def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert hasattr(x, "check") pytest discovers all tests following its Conventions for Python test discovery, so it finds both test_ prefixed functions.
🌐
GeeksforGeeks
geeksforgeeks.org › python › creating-instance-objects-in-python
Creating Instance Objects in Python - GeeksforGeeks
July 23, 2025 - Example 2: In this example, we create a base class Animal and a derived class Dog. We use super() to call the parent class constructor and set the species to "Dog" by default.
🌐
Python.org
discuss.python.org › python help
Understanding classes, init and self - Python Help - Discussions on Python.org
February 16, 2024 - I am learning and trying to get in touch with the logic of classes · The __init__ method initialises a new instance (object) of the class NewWindow. The actual creation of the instance is done by a separate method __new__, before __init__ is called.
🌐
Python.org
discuss.python.org › python help
Python Class tutorial - Python Help - Discussions on Python.org
April 30, 2023 - Hi there i have completed a an exercise from a book and wanted you guys to have a look, I think its giving me back the results needed but i cant tell for sure if i have answered the questions rightly and the code i wrote is not error prone. better coding suggestions are welcome: “”" User Class: Test 1: 1 Make a class called User.
🌐
UrbanPro
urbanpro.com › python › learn python
How do you create a Python class file? - UrbanPro
July 10, 2022 - Simply create a new file and define all the classes inside that file. thats it, you have created a class file. myClass.py to refer to those classes contained in myClass file, simply import it.