Can anyone explain in simple words what an attribute in Python language is?
For instance what can I say about
list.append(x)
which adds
Properties are just one thing that can be modeled using attributes. As you say, the operation of adding to the end of a list is another such thing. This has a rather straightforward interpretation in Python; since functions are first-class values, they can be stored as the value of an attribute like any other type. Here, list.append
is simply a function, which when called adds its argument to the end of list
. You can see that it doesn't matter by what name you call the function. The following are identical in behavior:
list.append(5)
f = list.append; f(5)
In both cases, the same bound method is called with an argument of 5.
See the python documentation : Especially 9.3.3. Instance Objects: There are two kinds of valid attribute names, data attributes and methods. You'll find there examples, too. So, why are methods also called attributes? For some methods the term "attribute" fits better, than for others. Example:
car.color()
This method may return the color of the car.
Take it just as a matter of definition and generalization that the word after the dot is called an attribute of the object before the dot.
You might put off explaining until you've introduced your student to class
and the idea that a function can be assigned to a variable just as a number or a data structure can be assigned. At this point it is obvious that a method is an attribute in the same way that a stored value is an attribute. Compare count and bump in
class Counter( object):
def __init__( self, initial=0):
self.count=initial
def bump(self):
self.count += 1
print( "count = {0}".format( self.count) )
count is an integer attribute. bump is a "bound method" attribute (commonly just called a method). list.append is another such attribute.
>>> d=Counter()
>>> d.bump()
count = 1
>>> d.bump
<bound method counter.bump of <__main__.counter object at 0x7fb5eb01db38>>
>>> d.count
1
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'bump', 'count']
(in particular the last two and your __init__
. The rest are inherited from object).
Alternatively, tell him that it's a method and don't (yet) mention that a method is an attribute. Attribute: data attached to an object. Method: function attached to an object (usually for the purpose of manipulating the attached data in some way).