10

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

1
  • 1
    Have you tried A.c = 3? Commented Jan 3, 2021 at 8:14

3 Answers 3

9

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Just add this line to your code:

A.c = 3

And then if you do:

print(A.c)

It will output:

3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.