How to explain an attribute in Python to a novice

后端 未结 3 975
甜味超标
甜味超标 2021-01-27 04:19

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

3条回答
  •  感动是毒
    2021-01-27 04:49

    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
    >
    >>> 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).

提交回复
热议问题