python - Different ways of calling class functions -


say have code:

class classstylea(object):     def functiona(self):         print "this style a."  class classstyleb(object):     def functiona(self):         print "this style b."  class instancestylea(classstylea):     def functionb(self):         print "this style a."  instancestyleb = classstyleb() 

if want call, example, functiona, instancestylea, need type this:

instancestylea().functiona() 

if want call functiona instancestyleb, need type this:

instancestyleb.functiona() 

i need add set of parentheses after instancestylea in order call 1 of functions, otherwise error:

typeerror: unbound method functiona() must called instancestylea instance first argument (got nothing instead) 

similarly, if try add parentheses after instancestyleb when calling 1 of it's functions, error:

typeerror: 'classstyleb' object not callable 

why case? why treated differently if both instances of class?

in example code, have 3 classes , 1 object, confusingly named:

  • classstylea class, inherits object
  • classstyleb class inherits object
  • instancestylea not instance, class, inherits classstylea.
  • instancestyleb not class, it's instance of class classstyleb

to create instance class, call class. so, classstylea(), classstyleb(), instancestylea() instances. instancestyleb - it's variable assign instance created classstyleb.

since instancestyleb (without parentheses) instance (of classstyleb), , not class, can't call it. explains second typeerror.

analogously, can call methods (functions defined in class, in example it's functiona , functionb) on instance. explains first typeerror: instancestylea (again, without parentheses), class.

(pedantic aside: of above is, technically speaking, utter lies, sake of discussion it's simpler pretend python has clear separation between classes , instances, , functions , methods.)


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -