5

I was reading through some code when I came across this particular code where the base class method is printing some attributes which are from derived class, the object which is calling the method is from derived.

class A(object):
  def printFreak(self):
    print self.derived_attrib

class B(A):
  def __init__(self, num):
    self.derived_attrib = num

my_obj = B(10)
my_obj.printFreak()

Since I had not seen such behaviour before(like in C++), I am unable to understand this.

Can anyone help me understand this, how this works ? Can this be related to some concept of C++ ?

6
  • 2
    In Python, attributes are resolved at run-time, so it simply looks for an attribute called derived_attrib in the object referred to by self, and finds that there is one. It would work in C++ as long as derived_attrib was declared as field of A and then assigned in B, because then the compiler would be able to figure out what self.derived_attrib meant in A's method. Commented Aug 18, 2016 at 10:02
  • 1
    C++ uses a strict memory layout, python uses a dictionary. Commented Aug 18, 2016 at 10:03
  • Thanks for the quick responses. And it's ok/legal to use such pattern or is it considered a misuse ? Commented Aug 18, 2016 at 10:52
  • 2
    @mittal It's not a great idea for a parent class to make assumptions about its child classes like that. It'd be better if the printFreak method were an attribute of the child class that defines .derived_attrib. In Python, it's quite common for attributes to be added dynamically to class instances, but it's still a bit smelly for a method to make assumptions about attributes that aren't part of the class definition (either in the class itself or defined in one of its parents). Commented Aug 18, 2016 at 11:15
  • @khelwood Would you mind posting your comment as an answer? I think this can be removed from the "unanswered" list. Commented Sep 13, 2018 at 13:43

1 Answer 1

3

In Python, attributes are resolved at run-time, so it simply looks for an attribute called derived_attrib in the object referred to by self, and finds that there is one.

It would work in C++ as long as derived_attrib was declared as field of A and then assigned in B, because then the compiler would be able to figure out what self.derived_attrib meant in A's method.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.