Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: changing methods and attributes at runtime

I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?

Oh, and please don't ask why.

like image 813
Migol Avatar asked Jun 07 '09 22:06

Migol


People also ask

Can you change class attributes in Python?

But be careful, if you want to change a class attribute, you have to do it with the notation ClassName. AttributeName. Otherwise, you will create a new instance variable.

Can methods have attributes in Python?

Everything in Python is an object, and almost everything has attributes and methods.

What is the difference between methods and attributes in Python?

A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.


2 Answers

This example shows the differences between adding a method to a class and to an instance.

>>> class Dog(): ...     def __init__(self, name): ...             self.name = name ... >>> skip = Dog('Skip') >>> spot = Dog('Spot') >>> def talk(self): ...     print 'Hi, my name is ' + self.name ... >>> Dog.talk = talk # add method to class >>> skip.talk() Hi, my name is Skip >>> spot.talk() Hi, my name is Spot >>> del Dog.talk # remove method from class >>> skip.talk() # won't work anymore Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk' >>> import types >>> f = types.MethodType(talk, skip, Dog) >>> skip.talk = f # add method to specific instance >>> skip.talk() Hi, my name is Skip >>> spot.talk() # won't work, since we only modified skip Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk' 
like image 176
Paolo Bergantino Avatar answered Oct 16 '22 01:10

Paolo Bergantino


I wish to create a class in Python that I can add and remove attributes and methods.

import types  class SpecialClass(object):     @classmethod     def removeVariable(cls, name):         return delattr(cls, name)      @classmethod     def addMethod(cls, func):         return setattr(cls, func.__name__, types.MethodType(func, cls))  def hello(self, n):     print n  instance = SpecialClass() SpecialClass.addMethod(hello)  >>> SpecialClass.hello(5) 5  >>> instance.hello(6) 6  >>> SpecialClass.removeVariable("hello")  >>> instance.hello(7) Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: 'SpecialClass' object has no attribute 'hello'  >>> SpecialClass.hello(8) Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: type object 'SpecialClass' has no attribute 'hello' 
like image 34
Unknown Avatar answered Oct 16 '22 02:10

Unknown