How to add attribute to class in python

Viewed 1365

I have:

class A:
        a=1
        b=2

I want to make as

setattr(A,'c')

then all objects that I create it from class A has c attribute. i did not want to use inheritance

3 Answers

There're two ways of setting an attribute to your class;

First, by using setattr(class, variable, value)

Code Syntax

setattr(A,'c', 'c')
print(dir(A))

OUTPUT

You can see the structure of the class A within attributes

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', 'a', 'b', 'c']

[Program finished]

Second, you can do it simply by assigning the variable

Code Syntax

A.d = 'd'
print(dir(A))

OUTPUT

You can see the structure of the class A within attributes

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', 'a', 'b', 'c', 'd']

[Program finished]

Just add this line to your code:

A.c = 3

And then if you do:

print(A.c)

It will output:

3
Related