The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) This is because it doesn't have a __dict__ to hold the attributes.


I generally just do this:

class Object(object):
    pass

obj = Object()
obj.somefield = "somevalue"

But consider giving the Object class a more meaningful name, depending on what data it holds.


Another possibility is to use a sub-class of dict that allows attribute access to get at the keys:

class AttrDict(dict):
    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        self[key] = value

obj = AttrDict()
obj.somefield = "somevalue"

To instantiate the object attributes using a dictionary:

d = {"a": 1, "b": 2, "c": 3}

for k, v in d.items():
    setattr(obj, k, v)
Answer from FogleBird on Stack Overflow
🌐
Hands-on
hands-on.cloud › home › uncategorized › python create object mastery: a comprehensive guide to object creation in python
Python Create Object Mastery: A Comprehensive Guide to Object Creation in Python
June 7, 2023 - You can create a Python object with attributes by defining a class with the desired attributes and initializing them within the init method.
Discussions

Shortest way of creating an object with arbitrary attributes in Python? - Stack Overflow
Unfortunately, most code I write is limited to Python 2.5, and namedtuple was added in 2.6. +1 though =) 2010-02-17T12:03:44.483Z+00:00 ... I just meant that I could go with a simpler solution, this solution has extra tuple functionality that I don't really need (plus it creates a whole new class; I was just interested in creating a single instance with the specified attributes ... More on stackoverflow.com
🌐 stackoverflow.com
Working with objects with many attributes - best approach?
To first reply to your concern about the "pythonic" way to do this, in scenarios like this it really comes down to what is the most concise, explicit, and logical way to do what you're trying to do. With that in mind, I'll have some suggestions for you. Given that when you are instantiating your Platform class, you already have access to all the xml elements/information, I think the most reasonable approach is to let the Platform class itself handle setting up all of its attributes for you. The more you can delegate pieces of code to their constituent parts, the better in my mind. as far as your suggested solutions, I think a combination would be best to keep your class more flexible for future potential uses. By that I mean adding an optuonal parameter for a list of the xml element objects you have in your outer for loop and making a method inside the Platform class that pulls out the constituent parts, as well as taking advantage of the **kwargs python parameter to allow the instance variables to be passed in manually as well. A simple way to do this is using the dictionaries get method and using the secondary default value parameter like so: self.variable = kwargs.get (var_name, default_value) An implementation like that, I think, will give you a very logical solution to your that is flexible and extensible for any unforseen future needs. Edit: I would recommend not using the set attr builtin for a situation like this, or if you do, only do so under the pretense of the has attr method. Remember the python guideline explicit is better than inplicit, and remember that with the code you have now, your Platform instances could end up with a bunch of attributes you may not have intended them to have. Which could cause confusion later on. I think in this case it's better to make sure you only process the xml elements you actually support in your Platform class, rather than adding any element in the xml you find to your class. Edit 2: the above also applies to the Platforms str method, printing out the classes entire dict is a little lazy and will give you a lot of clutter you probably don't care about (python builtin variables and the likes). Edit 3: it also kind of looks like everything other than the first 3 attributes of the class may be better suited in a dictionary object, perhaps named properties? That way your string method has less to do, and the kwargs dictionary could be precisely mapped to this internal dictionary. Using the python builtins getitem and setitem, you can emulate dictionary key access that can look inside this internal dictionary as well, so you could access these values from Platform as if platform itself were a dictionary. Just throwing this one out as something to keep in mind as it may be something you like or is helpful for your use case. More on reddit.com
🌐 r/learnpython
4
2
February 17, 2015
Can an object be an attribute of another object?
Yes. Token example: class Car: def __init__(self,model,cylinders): self.model = model self.engine = Engine(cylinders) class Engine: def __init__(self, cylinders): self.cylinders = cylinders my_car = Car("Honda CR-V",6) print(my_car.model) print(my_car.engine.cylinders) More on reddit.com
🌐 r/learnpython
4
1
August 27, 2022
dynamically add properties to a class (property, __getattribute__, something else?)

Properties must be defined on the class, not the instance. You're assigning the property on self when it needs to be assigned on A.

But dynamically creating attributes like this is weird and messy. The first thing you should do is reconsider whether you really do need to dynamically create attributes. It's an overly complex solution to most problems. Describing your problem to us might be helpful here. If you still decide you need this then you should use __getattr__ (and probably not __getattribute__). Properties are not the right solution.

More on reddit.com
🌐 r/learnpython
17
2
January 4, 2016
People also ask

How do you create an object in Python?
To create an object in Python, a few steps must be followed. First, you must create a class that will define the object with the "init()" constructor. Then the attributes of the object can be defined and more methods created.
🌐
study.com
study.com › computer science courses › computer science 113: programming in python
Creating Objects in Python | Definition, Syntax & Examples - Lesson ...
What does it mean to create an object in Python?
Creating an object in Python means that a target identifier will be created. This means that memory space will be allocated to hold the object and its information for use in a program, for example.
🌐
study.com
study.com › computer science courses › computer science 113: programming in python
Creating Objects in Python | Definition, Syntax & Examples - Lesson ...
What is an object in Python 3?
An object in Python represents an element in the computational domain. Objects are often used to represent real objects and have attributes (state variables) and methods that can modify these attributes.
🌐
study.com
study.com › computer science courses › computer science 113: programming in python
Creating Objects in Python | Definition, Syntax & Examples - Lesson ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-add-attribute-to-object
How to Add attributes to an Object in Python | bobbyhadz
Copied!from types import ... language='Python') print(obj1) The SimpleNamespace class is quite convenient when you need to create a blank object to which you can add attributes....
🌐
Iditect
iditect.com › faq › python › how-to-create-an-object-and-add-attributes-to-it-in-python.html
How to create an object and add attributes to it in python?
Description: This query addresses the basic process of creating a new object in Python and dynamically adding attributes to it. ... Description: Sometimes, you may need to add attributes to an object after its creation for flexibility and adaptability. ... class MyClass: pass obj = MyClass() setattr(obj, 'attribute1', "value1") setattr(obj, 'attribute2', 123) How to initialize an object with attributes in Python using the constructor?
Find elsewhere
🌐
Dive into Python
diveintopython.org › home › learn python programming › classes in python › class objects in python
Class Objects in Python: How to Create an Object, How to Get Attributes
May 3, 2024 - We've created two objects (car1 and car2) from the Car class. We've passed in values for the make, model, and year attributes for each car. We've then called the display() method on each object to print information about the car. To summarize, classes and objects in Python are used to create custom data types that can have attributes and methods.
🌐
Study.com
study.com › computer science courses › computer science 113: programming in python
Creating Objects in Python | Definition, Syntax & Examples - Lesson | Study.com
July 1, 2025 - ... To declare attributes in a Python class, they have to be defined in a special method called "init()", which initializes the state of an object. This method also defines the constructor of the class, allocating space in the memory for the object.
🌐
Real Python
realpython.com › python-property
Python's property(): Add Managed Attributes to Your Classes – Real Python
April 17, 2026 - Once you have these three methods in place, you create a class attribute called .radius to store the property object. To initialize the property, you pass the three methods as arguments to property(). You also pass a suitable docstring for your property. In this example, you use keyword arguments to improve readability and prevent confusion. That way, you know exactly which method goes into each argument. To give Circle a try, run the following code in your Python REPL:
🌐
LabEx
labex.io › tutorials › python-how-to-initialize-python-object-attributes-415187
How to initialize Python object attributes | LabEx
Here are some recommended best practices: Whenever possible, use the __init__ method to initialize object attributes. This ensures that all necessary attributes are set when the object is created, making the object's state more predictable and ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
Attributes can be accessed using dot (.) operator (e.g., MyClass.my_attribute). ... 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
🌐
Medium
medium.com › @nschairer › python-dynamic-class-attributes-24a89df8da7d
Python — Dynamic Class Attributes | by noah | Medium
February 5, 2022 - But what if you don’t know what the attributes name is suppose to be? For an object it’s as simple as obj[‘NAME OF ATTR’] = value, but for a class you cannot index with brackets.
🌐
Vultr Docs
docs.vultr.com › python › built-in › setattr()
Python setattr() - Set Attribute Value
September 27, 2024 - This snippet demonstrates creating completely new attributes (identifier and contents) for an instance of a class that initially does not have any predefined attributes. The setattr() function in Python serves as a valuable tool for managing object attributes dynamically.
🌐
Reddit
reddit.com › r/learnpython › working with objects with many attributes - best approach?
r/learnpython on Reddit: Working with objects with many attributes - best approach?
February 17, 2015 -

I'm working on my own version of thegamesdb api for python and I'm having an internal struggle over the best way to handle multiple sub-elements for items. For example, when you call the GetPlatform API, each platform object can have many elements. I want to create a platform object that contains all of those attributes, but I'm not sure if I should create a new Platform object within the XML parsing method and then modify the object as I read the items, read all the items first into variables and call the Platform object with a dozen or more arguments, pass a dictionary to the Platform object and parse it within init, or maybe even another idea I've yet to think of.

My current strategy is to create a new Platform object with just the id and name, then use the setattr() method on the object as I iterate over the elements, but I'm not sure if this is pythonic or not.

Any suggestions or resources on how this could should be properly written?

Github link

Top answer
1 of 1
2
To first reply to your concern about the "pythonic" way to do this, in scenarios like this it really comes down to what is the most concise, explicit, and logical way to do what you're trying to do. With that in mind, I'll have some suggestions for you. Given that when you are instantiating your Platform class, you already have access to all the xml elements/information, I think the most reasonable approach is to let the Platform class itself handle setting up all of its attributes for you. The more you can delegate pieces of code to their constituent parts, the better in my mind. as far as your suggested solutions, I think a combination would be best to keep your class more flexible for future potential uses. By that I mean adding an optuonal parameter for a list of the xml element objects you have in your outer for loop and making a method inside the Platform class that pulls out the constituent parts, as well as taking advantage of the **kwargs python parameter to allow the instance variables to be passed in manually as well. A simple way to do this is using the dictionaries get method and using the secondary default value parameter like so: self.variable = kwargs.get (var_name, default_value) An implementation like that, I think, will give you a very logical solution to your that is flexible and extensible for any unforseen future needs. Edit: I would recommend not using the set attr builtin for a situation like this, or if you do, only do so under the pretense of the has attr method. Remember the python guideline explicit is better than inplicit, and remember that with the code you have now, your Platform instances could end up with a bunch of attributes you may not have intended them to have. Which could cause confusion later on. I think in this case it's better to make sure you only process the xml elements you actually support in your Platform class, rather than adding any element in the xml you find to your class. Edit 2: the above also applies to the Platforms str method, printing out the classes entire dict is a little lazy and will give you a lot of clutter you probably don't care about (python builtin variables and the likes). Edit 3: it also kind of looks like everything other than the first 3 attributes of the class may be better suited in a dictionary object, perhaps named properties? That way your string method has less to do, and the kwargs dictionary could be precisely mapped to this internal dictionary. Using the python builtins getitem and setitem, you can emulate dictionary key access that can look inside this internal dictionary as well, so you could access these values from Platform as if platform itself were a dictionary. Just throwing this one out as something to keep in mind as it may be something you like or is helpful for your use case.
🌐
Delft Stack
delftstack.com › home › howto › python › python add attribute to object
How to Add Attribute to Object in Python | Delft Stack
February 2, 2024 - Name - It will be the name of the attribute of that object that we want to assign value to. Value - We will pass the attribute value here. Let’s go through an example in which we will create a class of students. We will create a new student and assign it some attributes, as shown below. # python class Students: name = "Rana Hasnain" roll_no = "BC140402269" cgpa = 3.5 new_student = Students() setattr(new_student, "name", "James Bond") setattr(new_student, "roll_no", "007") setattr(new_student, "cgpa", 4) print("New Student Name:", new_student.name) print("New Student Roll #:", new_student.roll_no) print("New Student Cgpa:", new_student.cgpa)
🌐
Medium
medium.com › @winnydid › object-and-class-attributes-in-python-explained-with-examples-a9ecb7cf8ae7
Object and Class Attributes in Python: Explained with Examples | by Winny Didine Ineza | Medium
March 17, 2023 - In Python, a class is a blueprint or a template for creating objects, while an object is an instance of a class. A class can be thought of as a user-defined data type that contains attributes (variables) and methods (functions) that define the behavior of the objects created from it. It allows you to create multiple objects that share the same characteristics and behavior, without having to write the same code over and over again.
🌐
Medium
medium.com › swlh › class-and-object-attributes-python-8191dcd1f4cf
Class and Object Attributes — Python | by Ethan Mayer Bloom | The Startup | Medium
December 30, 2019 - class Example: classAttr = 0 def __init__(self, instanceAttr): self.instanceAttr = instanceAttra = Example(1) print(a.__dict__) print(Example.__dict__)Output: {'instanceAttr': 1} {'__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'Example' objects>, '__init__': <function Example.__init__ at 0x7f8af2113f28>, 'classAttr': 0, '__weakref__': <attribute '__weakref__' of 'Example' objects>} As we can see, both the class and the object have a dictionary with attribute keys and values.
🌐
Medium
medium.com › @suryansaravanan › dynamic-attribute-manipulation-in-python-d34bd6c3c2d7
Dynamic Attribute Manipulation in Python | by Suryan Saravanan | Medium
July 8, 2023 - In the above example, we create a Person object with name and age attributes. Using setattr(), we set the age attribute to None and then delete it using delattr(). As a result, when we attempt to access the age attribute, Python raises an AttributeError since the attribute no longer exists.
🌐
freeCodeCamp
freecodecamp.org › news › python-attributes-class-and-instance-attribute-examples
Python Attributes – Class and Instance Attribute Examples
April 12, 2022 - To create a class in Python, we use the class keyword followed by the name of the class. Here is an example: class Student: name = "Jane" course = "JavaScript" In the code above, we created a class called Student with a name and course property. Now let's create new objects from this class. class Student: name = "Jane" course = "JavaScript" Student1 = Student() print(Student1.name) # Jane · We've created a new object called Student1 from the Student class.
🌐
HCL GUVI
studytonight.com › python-howtos › how-to-create-objects-in-python
HCL GUVI | Learn to code in your native language
April 12, 2023 - My mentors used to explain concepts in Tamil in really clear-cut ways.Placement support along with mock interviews and job-specific prep sessions was very useful. ... HCL GUVI's Data Science Program was just fantastic. It covered statistics, machine learning, data visualization, and Python within its curriculum.