27

if I have something like

import mynewclass 

Can I add some method to mynewclass? Something like the following in concept:

def newmethod(self,x): return x + self.y mynewclass.newmethod = newmethod 

(I am using CPython 2.6)

1

2 Answers 2

43

In Python the import statement is used for modules, not classes... so to import a class you need something like

from mymodule import MyClass 

More to the point of your question the answer is yes. In Python classes are just regular objects and a class method is just a function stored in an object attribute.

Attributes of object instances in Python moreover are dynamic (you can add new object attributes at runtime) and this fact, combined with the previous one means that you can add a new method to a class at runtime.

# define a class with just one attribute class MyClass: def __init__(self, x): self.x = x # creates an instance of the class obj = MyClass(42) # now add a method to the class def new_method(self): print("x attribute is", self.x) MyClass.new_method = new_method # the method can be called even on already existing instances obj.new_method() 

How can this work? When you type

obj.new_method() 

Python will do the following:

  1. look for new_method inside the object obj.

  2. Not finding it as an instance attribute it will try looking inside the class object (that is available as obj.__class__) where it will find the function.

  3. Now there is a bit of trickery because Python will notice that what it found is a function and therefore will "wrap" it in a closure to create what is called a "bound method". This is needed because when you call obj.new_method() you want to call MyClass.new_method(obj)... in other words binding the function to obj to create the bound method is what takes care of adding the self parameter.

  4. This bound method is what is returned by obj.new_method, and then this will be finally called because of the ending () on that line of code.

If the search for the class also doesn't succeed instead parent classes are also all searched in a specific order to find inherited methods and attributes and therefore things are just a little bit more complex.

Sign up to request clarification or add additional context in comments.

1 Comment

Could be used like: py import turtle def rect(self, width, height): self.setheading(0) for count in range(4): if count % 2 == 0: self.forward(length) self.right(90) else: self.forward(height) self.right(90) turtle.Turtle.rect = rect
6

Yes, if it's a Python type. Except you'd do it on the class, not the module/package.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.