In Python you can add members dynamically to an object, but (1) the name must already exist (it must have been assigned) and (2) it must be bound to an instance of some class. To do so you may create an empty class:

class Empty:
    pass        # empty statement otherwise the class declaration cannot succeed

construct an instance of it and assign it to your variable

person = Empty()

and then add whatever data you want

person.name = 'Mike'
person.age = 25
person.gender = 'male'

On the other hand, if you don't need the additional features a "normal" class provides and you just want to store some data in a key=>value fashion you should probably just use a dictionary.

person={}
person['name']='Mike'
person['age']=25
person['gender']='male'

(notice that, at least up to Python 2.7, this is mostly just a stylistic/syntactic difference, since instance members are implemented underneath in terms of dictionaries)

As a general guideline, you want classes when you are instantiating multiple objects made in the same way (and where typically the assignment to the members is done in the class constructor; adding members later generally makes for difficult to follow code), dictionaries otherwise.

Answer from Matteo Italia on Stack Overflow
Top answer
1 of 6
33

In Python you can add members dynamically to an object, but (1) the name must already exist (it must have been assigned) and (2) it must be bound to an instance of some class. To do so you may create an empty class:

class Empty:
    pass        # empty statement otherwise the class declaration cannot succeed

construct an instance of it and assign it to your variable

person = Empty()

and then add whatever data you want

person.name = 'Mike'
person.age = 25
person.gender = 'male'

On the other hand, if you don't need the additional features a "normal" class provides and you just want to store some data in a key=>value fashion you should probably just use a dictionary.

person={}
person['name']='Mike'
person['age']=25
person['gender']='male'

(notice that, at least up to Python 2.7, this is mostly just a stylistic/syntactic difference, since instance members are implemented underneath in terms of dictionaries)

As a general guideline, you want classes when you are instantiating multiple objects made in the same way (and where typically the assignment to the members is done in the class constructor; adding members later generally makes for difficult to follow code), dictionaries otherwise.

2 of 6
19

Python won't magically create a container object when you start assigning attributes to it, and if matlab allows this, I'd consider matlab badly broken. Consider this:

person.name = "Mike"
persom.age  = 25
person.sex  = "Male"

Now we have two objects, person and persom, and person doesn't have age, and there was no hint that this happened. Later you try to print person.age and, one would hope, matlab then complains... two pages after the actual mistake.

A class can itself be used as a container or namespace. There's no need to instantiate it, and it'll save you a bit of typing if you just want a bundle of attributes.

class sex:
    male   = "M"
    female = "F"

class person:
    name = "Mike"
    age  = 25
    sex  = sex.male

To access or modify any of these, you can use person.name, etc.

N.B. I used a class for sex as well to illustrate one of the benefits of doing so: it provides consistency in data values (no remembering whether you used "M" or "Male" or "male") and catches typos (i.e. Python will complain about sex.mlae but not about the string "mlae" and if you were later checking it against "male" the latter would fail).

Of course, you still run the risk of misspelling name, age, or sex in this type of class definition. So what you can do is use the class as a template and instantiate it.

class Person:
    def __init__(self, name, age=None, sex=None):
        self.name, self.age, self.sex = name, age, sex

Now when you do:

person = Person("Mike", 25, sex.male)

or if you want to document what all those parameters are:

person = Person("Mike", age=25, sex=sex.male)

it is pretty much impossible to end up with an object that has a misspelled attribute name. If you mess it up, Python will give you an error message at the point you made the mistake. That's just one reason to do it this way.

🌐
Reddit
reddit.com › r/python › how to create classes without the class keyword
r/Python on Reddit: How to create classes without the class keyword
July 2, 2022 -

In Python, we learn that in order to create a class you need to start off with the `class` keyword. But the reality is that we actually don't.

I've written an article on how this works. We take a deeper dive into data types in Python and explore how they work under the hood.

I explore how all data types are classes, and how they can all be derived from `type` which by the way can do more than tell you the type of an object! Check out the article below if this sounds intriguing.

https://medium.com/@Salaah01/creating-a-class-in-python-without-the-class-keyword-67ce84bae22

Edit: Oh, and don't worry. The point of the article isn't to say. "Hey guys, this is a new way to write classes, and this is what you should do from now on". In the article, I explicitly discourage that. Instead, it's to give an inside to how it works and why it works.

Discussions

How do I create an object that has no class in Python? - Stack Overflow
I am using the object function (object()) to make an object without a class in Python but it does not have any attributes or arguments, so I am trying to customise it by creating a variable like th... More on stackoverflow.com
🌐 stackoverflow.com
design - Can you implement "object-oriented" programming without the class keyword? - Software Engineering Stack Exchange
If you're interested, you can read ... where I create a simple object system in JavaScript without relying on any of the OOP parts of the language. Your 1st example has an important shortcoming: Where you'd write object['method'](args), Python objects actually do the equivalent of object['method'](object, args). This becomes relevant when a base class calls methods ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
How is this code creating objects without constructors or instance attributes? Please see the description
SQLAlchemy allows the creation of model class by extending the db.Model And in the model class we declare class attributes instead of instance attributes. Why is that ? My guess is because the instance variables are used to access the value in the instance, and class attributes are used to define the type and give information about these attributes. We don't even have a constructor or init method and yet we are able to create objects by passing arguments (and that too on the freaking class attributes). How is this working ? The constructor is defined by db.Model, and you extending it inherits that constructor. More on reddit.com
🌐 r/learnpython
2
1
June 28, 2023
Can I create a class without constructor? (details in the post)

You can use static or class methods for classes:

class MyClass:
    @classmethod
    def my_func(cls, p1, p2):
        return [p1, p2]

and then you can call it like this: MyClass.my_func(1, 2)

I hope this is what you asked.

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner

More on reddit.com
🌐 r/learnpython
3
1
March 17, 2018
🌐
Quora
quora.com › Is-it-possible-to-initialize-objects-without-explicitly-creating-them-using-classes-in-Python
Is it possible to initialize objects without explicitly creating them using classes in Python? - Quora
Sure, you can get into metaclasses and all of that but it’s not really important to be able to use classes in Python effectively. The only things you really need to implement to make a class useful are the __init__ method and another other methods you would like to make public on the objects that you create.
🌐
Plain English
python.plainenglish.io › creating-a-class-in-python-without-the-class-keyword-67ce84bae22
Create a Class in Python Without the Class Keyword | by Salaah Amin | Python in Plain English
July 6, 2022 - We will explore how you can create a class in Python without using the class keyword. Whilst this exploration you will learn what a class another all other data types are really under the hood.
Top answer
1 of 6
64

Congratulations! You rediscovered the well known fact that object orientation can be done without specific programming language support. It is basically the same way objects are introduced in Scheme in this classic text book. Note that Scheme does not have a class keyword or some kind of equivalent, and objects can be created without having even classes.

However, the object orientated paradigm was so successful that lots of languages - and Python is no exception - provide built-in support for it. This is simply to make it easier for developers to use the paradigm and to provide a standard form of object orientation for that language. It is essentially the same reason why lots of languages provide a for loop, though it could be emulated using a while loop with just one or two additional lines of code - simply ease of use.

2 of 6
12

I would agree that the first definition satisfies the three points your teacher made. I do not think we need the class keyword for anything. Under the covers, what else is an object but a data structure with with different types of data and functions to work with the data? Of course, the functions are data as well..

I would go even further and say that doing object oriented programming is not so much dependent on the keywords your language provides, you can do object oriented programming in C if you so wished! In fact, the linux kernel employs such techniques.

What you can infer from the class keyword here is, that the language provides support for this kind of construct out of the box, and you do not need to through all the hoops to re-implement the functionality yourself(which is pretty fun task in itself!). Not to mention all the syntactic sugar you might get as well.

🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.4 documentation
Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used… · Actually, you may have guessed the answer: the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.
Find elsewhere
🌐
Quora
quora.com › When-I-create-a-Python-method-without-creating-a-class-I-dont-need-to-define-self-as-a-default-method-parameter-but-when-I-put-the-method-in-a-class-I-need-to-put-self-Why-is-this
When I create a Python method without creating a class, I don't need to define 'self' as a default method parameter, but when I put the method in a class I need to put 'self'. Why is this? - Quora
Here I have created the object, Will. ... So, self-represents the object itself. The Object is will. Then I have defined a method speak_name. ( A method is different from Function because it is part of the class) It can be called from the object. Self is an object when you call self, it refers to will. This is how self-works. Whenever you use self. something, actually you’re assigning new value or variable to the object which can be accessed by the python program everywhere.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
__str__ Implementation: Defined as a method in Dog class. Uses self parameter to access instance's attributes (name and age). Readable Output: When print(dog1) is called, Python automatically uses __str__ method to get a string representation of object. Without __str__, calling print(dog1) would produce something like <__main__.Dog object at 0x00000123>.
Published   3 weeks ago
🌐
Real Python
realpython.com › python-class-constructor
Python Class Constructors: Control Your Object Instantiation – Real Python
January 19, 2025 - Note: Most experienced Python ... in Python unless you already have a working class and need to add the pattern’s functionality on top of it. The rest of the time, you can use a module-level constant to get the same singleton functionality without having to write a relatively complex class. Here’s an example of coding a Singleton class with a .__new__() method that allows the creation of only one ...
🌐
TutorialBrain
tutorialbrain.com › home › python create object
Python Create Object — TutorialBrain
July 9, 2025 - Creating empty objects in Python is easy. Define an empty class and then create an object of that class. Let’s check that in the example below · But what if you want to create an empty object without explicitly creating an empty class?
🌐
Reddit
reddit.com › r/learnpython › how is this code creating objects without constructors or instance attributes? please see the description
r/learnpython on Reddit: How is this code creating objects without constructors or instance attributes? Please see the description
June 28, 2023 -

I'm working with Flask and using SQL Alchemy ORM and there is something I would like to understand in the code. SQLAlchemy allows the creation of model class by extending the db.Model And in the model class we declare class attributes instead of instance attributes. Why is that ?

We don't even have a constructor or __init__ method and yet we are able to create objects by passing arguments (and that too on the freaking class attributes). How is this working ?

from flask_sqlalchemy import SQLAlchemy

from flask import Flask

app = Flask(name) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app)

class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False)

def __repr__(self):
    return f"User('{self.username}', '{self.email}')"

with app.app_context(): db.create_all()

# how is the user getting created here with any init method in the User class
user1 = User(username="foo", email="foo@demo.com", password="foobar")
print(user1)
db.session.add(user1)
db.session.commit()
print(User.query.all())

🌐
Python Forum
python-forum.io › thread-40049.html
Possible to create an object inside another object that is visible outside that objec
May 24, 2023 - I know it sounds confusing so I'll try to illustrate the question in Main: self.myobj = myclass self.myobj(parameters)the object code class myobj(object) def __init__(self, ...): def mymethod((self,
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes/Objects
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.
🌐
Sololearn
sololearn.com › en › Discuss › 2941542 › pythonclass-without-__init__-still-works
(python)class without __init__ still works? | Sololearn: Learn to code for FREE!
Simon Sauter It's true. Explicitly writing __init__ makes it possible to set default parameters and object behavior, but even without explicit __init__ will be called when the object is created ... The reason is that in Python 3 all classes inherit from the object class.
🌐
Reddit
reddit.com › r/learnpython › can i create a class without constructor? (details in the post)
r/learnpython on Reddit: Can I create a class without constructor? (details in the post)
March 17, 2018 -

Hi!

When I need data to have a special structure and special properties I can create a custom object and its constructor in a custom class without problem. I can create methods in the class to do stuff with the object as well. That I have done and can do just fine.

Now I have a set of functions that only take numbers (some floats, some integers) as argument and return numbers (usually in an array). Can I still put them in a class if the class has no constructor? Is it better to come up with something that could be an object and to create a class with a constructor for this object + the functions that now will be applied to this object?

At the moment my program works just fine but I'm self-taught and I obviously didn't do it the right way. I'm just using it to automate things so that's fine but I may have to give it to people, which is why I'd like to improve and to rewrite it more clean.

Thanks in advance for your help!

🌐
Quora
quora.com › What-happens-if-you-define-a-python-class-without-an-__init__-function
What happens if you define a python class without an __init__ function? - Quora
Python doesn’t work that way. Variables need to be target of an assignment to be created in Python. So, if in a Python class, I wanted to ensure that there were three variables, a, b, and c, in every instance (object) of that class, I would in fact need an __init__ function…
🌐
Medium
medium.com › data-science › python-init-is-not-a-constructor-a-deep-dive-in-python-object-creation-9134d971e334
Python: __init__ is NOT a constructor: a deep dive in Python object creation | by Mike Huls | TDS Archive | Medium
February 29, 2024 - Python: __init__ is NOT a constructor: a deep dive in Python object creation Tinkering with Python’s constructor to create fast, memory-efficient classes Did you know that the __init__ method is …
🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-the-factory-pattern-in-python-a-practical-guide
How to Use the Factory Pattern in Python - A Practical Guide
February 9, 2026 - In this tutorial, you'll learn what the factory pattern is, why it's useful, and how to implement it in Python. We'll build practical examples that show you when and how to use this pattern in real-world applications.
🌐
Studytonight
studytonight.com › python-howtos › how-to-create-objects-in-python
How to create Objects in Python - Studytonight
April 12, 2023 - In this article, we will learn to create an object in Python. We will look at the methodology, syntax, keywords, associated terms with some simple approaches, and some custom codes as well to better understand this topic. Let's first have a quick look over what is an object, and how it is used and defined in Python language. An object is the run time entity used to provide the functionality to the Python class.