What is a method attribute, and a data attribute? What the difference between them and what they have in common?
I was reading python 2.7.9 (https://docs.python.org/
An attribute is basically anything that you can do instance.attribute_name
with. For instance in:
class Hello(object):
def __init__(self, word):
self.word = word
def greet(self):
print "Hello: "+self.word
__init__
, greet
and word
would all be attributes. I would guess that a method is anything that is declared with def at the class scope (as opposed to doing self.func = lambda x:x*x for instance). In this case you get into bound vs unbound methods and the like. The important part being that for a member attribute when you do instance.method_name
you get back a bound method, which when you call it will call the original method with the instance as the first argument.
Also, after reading some of that section their wording is somewhat confusing/erroneous. For instance they say "Data attributes override method attributes with the same name", which as far as I know would be better put as instance attribute override class attributes with the same name. From the example I gave if we expanded this to:
class Hello(object):
greeting = "Hello: "
def __init__(self, word):
self.word = word
def greet(self):
print self.greeting+self.word
Then we could do:
>>> a = Hello("world")
>>> a.greeting = "Goodbye "
>>> a.greet()
"Goodbye world"
This due to the fact that we put an instance attribute of greeting over the class attribute of greeting. Since methods defined in the class (the usual way) are class attributes they will be overridden by any instance attributes (data or otherwise).