0

I have a class called Image

class Image(object):
    def __init__(self,rgb_img):
        self.img_time = time.time()
        self.img_colr = rgb_img

I want to store some more information on this class at a later time (image keypoints, grey scale, etc.) and believe it is more clear to make a new class altogether. But I don't know the best practice for this. Heres my guess:

img = Image(rgb_img)
class DetailedImage(object):
    def __init__(self, img, kp, grey):
        self = img
        self.kp = kp
        self.grey = grey

Still, this option is implicit. It is not immediately obvious that the img argument must be an Image instance.

What is the best practice for creating a new class using an instance from another class? (i.e. if I have a peasant, and he trains to become a warrior, how to I pass information from the instantiated peasant class to a separate warrior class?) Is this even a good idea to do?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Paul Seeb
  • 6,006
  • 3
  • 26
  • 38
  • Your approach is probably not achieving what you want to do – see http://stackoverflow.com/questions/1216356/is-it-safe-to-replace-a-self-object-by-another-object-of-the-same-type-in-a-meth – wonce Jun 04 '14 at 20:11
  • Idea of assigning to self makes me cringe! Why not just inherit, if you must inherit --- use compositon. – jb. Jun 04 '14 at 21:32
  • @jb Care to submit an answer? This is literally the exact reason I asked the question. Need help with implementation/best practice. – Paul Seeb Jun 04 '14 at 21:54
  • @PaulSeeb here you go! – jb. Jun 05 '14 at 12:52

2 Answers2

1

As I've said in the comment: assigning to self makes me cringe, don't do that.

Apart from that you'll have many options how to get what you need.

Use composition:

class DetailedImage(object): 

    def __init__(self, img): 
        """
        :param Image img: Internal image 
        """
        self.img = img

In this case I specified parameter type using docstrings in sphinx format.

Use normal python inheritance.

Python inheritance (even multiple-inheritance) is usefull, and better than in other languages. I'd rathere refer you to the docs, than write too long answer. Or see this: How does Python's super() work with multiple inheritance?.

jb.
  • 23,300
  • 18
  • 98
  • 136
0

You can simply add any attribute to python class instances, you don't need to define a special class:

img = Image(rgb_img)
img.kp = kp
img.grey = grey
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • I want to be explicit about what data is on the class. Arbitrarily adding attributes is pretty hard to follow in larger programs. – Paul Seeb Jun 04 '14 at 20:16
  • You only know, what data is on a class if you keep it separate from classes, that don't have this attribute. – Daniel Jun 04 '14 at 20:20