1

I have a class C and a method f. I want f to behave differently for a few instances.

For example, if my class is Animal and f is printing "I'm a" and the animal name, I'd like :

cat.f() prints "I'm a cat"
dog.f() prints "I'm a dog"
puma.f() prints "I'm a BIG puma"

The behavior of f change for puma. And it could be much different than just a word. I could use derived classes but it seems heavy for such a thing. What's the cleanest way to do it ?

Rodolphe LAMPE
  • 1,346
  • 2
  • 11
  • 17
  • If your 'animals' inherit from `Animal` you should read [this post](http://stackoverflow.com/questions/6943182/get-name-of-current-class) – t.m.adam Apr 16 '17 at 10:08

1 Answers1

0

That's exactly what inheritance is for. And it's not too heavy - that is the cleanest and the most expected solution to such a problem.

There's no way to tell the variable name of the object from inside that object, so if you want an instance-specific behaviour, you could also preconfigure these instances like so:

class Animal:
    def __init__(self, name):
        self.name = name

    def f(self):
        print("I'm a", self.name)

    def set_name(self, new_name):
        self.name = new_name
illright
  • 3,991
  • 2
  • 29
  • 54