Reputation: 825
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
Upvotes: 8
Views: 14450
Reputation: 904
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]
Upvotes: 8
Reputation: 186
You can you static or class variables.
You can do A.c in your Code.
When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.
You can refer this https://www.tutorialspoint.com/class-or-static-variables-in-python#:~:text=When%20we%20declare%20a%20variable,not%20directly%20through%20an%20instance.
Upvotes: 2
Reputation: 71560
Just add this line to your code:
A.c = 3
And then if you do:
print(A.c)
It will output:
3
Upvotes: 1