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
34

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.

🌐
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.
🌐
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
Answer (1 of 2): If you don't create them, they don't exist. But the process of initialization involves creating them. You go to a bank, you can't deposit if your savings account has not been created. They cannot initialize it with an initial deposit. Creating means allocating physical memory to ...
🌐
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())

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.

Find elsewhere
🌐
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!

🌐
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.
🌐
TutorialBrain
tutorialbrain.com › home › python create object
Python Create Object — TutorialBrain
July 9, 2025 - You can create an object like as shown below. A Python object is an instant of the defined class and thus creating a new object from a class is called instantiation .
🌐
Reddit
reddit.com › r/learnpython › how to create an object without making a class for it?
r/learnpython on Reddit: How to create an object without making a class for it?
December 30, 2019 - ... You can use a dict or use a namedtuple if you want to store data. namedtuples have the advantage that they allow you to use the dot operator and make it seem as if you had created your own class for your object.
🌐
Real Python
realpython.com › python-class-constructor
Python Class Constructors: Control Your Object Instantiation – Real Python
October 21, 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 ...
🌐
Reddit
reddit.com › r/learnpython › can you make a class instance without making up a name for it?
r/learnpython on Reddit: Can you make a class instance without making up a name for it?
August 4, 2019 -

Hi! I am making a login system in Python3. It's just for practice so I am not actually going to use it for anything.

I wanted to use classes to learn how to use those. I plan on some day learning Java, so I thought it might be a good idea familiarising myself with the basic concepts of objective-oriented programming already now.

I have just created a class and the initiation method. I then wanted to make a function that I can use to create a user for my login system.

import getpass

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password
    
def add_user():
    username = input("Type a username: ")
    password = getpass.getpass(prompt="Type a password: ")

The problem is that, as far as I have understood the way you make an instance (e.g. user1) is:

user1 = User(username, password)

The thing is, I want my 'add-user()' command just add a new instance to the class without me having to name it (e.g. user1) every time.

I really hope this post isn't completely incomprehensible...

🌐
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…
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
An object is a specific instance of a class. It holds its own set of data (instance variables) and can invoke methods defined by its class. Multiple objects can be created from same class, each with its own unique attributes.
Published: 3 weeks ago
🌐
Python Forum
python-forum.io › thread-40049.html
Possible to create an object inside another object that is visible outside that objec
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, ...): my2ndobjinfirstobj ...
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.8 documentation
1 week ago - Each value is an object, and therefore has a class (also called its type). It is stored as object.__class__. Of course, a language feature would not be worthy of the name “class” without supporting inheritance.
🌐
HCL GUVI
studytonight.com › python-howtos › how-to-create-objects-in-python
HCL GUVI | Learn to code in your native language
April 12, 2023 - HCL GUVI's Data Science Program was just fantastic. It covered statistics, machine learning, data visualization, and Python within its curriculum.