1

I've been programming with python 3 for over about 3 - 4 months now. I'm currently learning Object Oriented Programming, analysis and design. So as I went through the journey, I saw special methods. I'm a little confused. I don't understand them. I know that __init__ is a special method and it runs every time we create an instance. I was just wondering if the other special methods runs the same way as the __init__ method or like a normal method

Thanks

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Marc2001
  • 281
  • 1
  • 3
  • 12
  • These methods are "special" in the sense that Python calls them automatically to implement various operations - for example, an `__add__()` method is how you'd implement addition (via the ordinary `+` operator) of instances of your class. They're not actually any different from ordinary methods, except that you don't usually call them directly (except in subclasses, to call the inherited version of the method from the superclass). – jasonharper May 13 '18 at 04:04
  • So, they won't be called automatically? But when I used the getattr method, it runs automatically and it doesn't matter what the name is – Marc2001 May 13 '18 at 07:50
  • Here's the code – Marc2001 May 13 '18 at 07:50
  • `class Foo: def __getattr__(self, key): print(key) bar = Foo() bar.hello()` The output gives me hello and an error "TypeError: 'NonType' object is not callable". Somehow, I can replace the hello with anything I want. Can you explain me? – Marc2001 May 13 '18 at 07:58
  • `bar.hello` has a value of `None`, because your `__getattr__()` did not return anything. And `None()` fails, of course - as the error message says, it's not a callable object. For `bar.hello()` to be meaningful in the absence of an actual `hello()` method, your `__getattr__()` would need to return a function or other callable object. – jasonharper May 13 '18 at 14:04

0 Answers0