How to add attribute to class in python

2024/10/12 14:18:31

I have:

class A:a=1b=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

Answer

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]
https://en.xdnf.cn/q/69641.html

Related Q&A

Number of occurrence of pair of value in dataframe

I have dataframe with following columns:Name, Surname, dateOfBirth, city, countryI am interested to find what is most common combination of name and surname and how much it occurs as well. Would be nic…

how do i dump a single sqlite3 table in python?

I would like to dump only one table but by the looks of it, there is no parameter for this. I found this example of the dump but it is for all the tables in the DB: # Convert file existing_db.db to SQL…

Django automatically create primary keys for existing database tables

I have an existing database that Im trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently Im able to import the models into the python shell h…

matplotlib.pyplot scatterplot legend from color dictionary

Im trying to make a legend with my D_id_color dictionary for my scatterplot. How can I create a legend based on these values with the actual color? #!/usr/bin/python import matplotlib.pyplot as plt f…

Numpy Array Set Difference [duplicate]

This question already has answers here:Find the set difference between two large arrays (matrices) in Python(3 answers)Closed 7 years ago.I have two numpy arrays that have overlapping rows:import numpy…

Pylint not working within Spyder

Ive installed Anaconda on a Windows computer and Spyder works fine, but running pylint through the Static Code Analysis feature gives an error. Pylint was installed through Conda. Note: Error in Spyder…

WTForms doesnt validate - no errors

I got a strange problem with the WTForms library. For tests I created a form with a single field:class ArticleForm(Form):content = TextField(Content)It receives a simple string as content and now I use…

NameError: global name numpy is not defined

I am trying to write a feature extractor by gathering essentias (a MIR library) functions. The flow chart is like: individual feature extraction, pool, PoolAggregator, concatenate to form the whole fea…

Django exclude from annotation count

I have following application:from django.db import modelsclass Worker(models.Model):name = models.CharField(max_length=60)def __str__(self):return self.nameclass Job(models.Model):worker = models.Forei…

How to use yield function in python

SyntaxError: yield outside function>>> for x in range(10): ... yield x*x ... File "<stdin>", line 2 SyntaxError: yield outside functionwhat should I do? when I try to use …