I have been reading a lot about Python OOP here and in the Python tutorial. But some questions bug me on class attributes.
Example:
class Par(object):
def __init__(self, chip, fig):
self.fruit = chip
self.fig = fig
self.pear =10
- Shouldn’t
self.fruit = chipbeself.chip = chip? - How come
fruitdoes not appear in the attribute list in the__init__()brackets but it is used? - What is the difference between
self.fruit = chipandself.chip = chip? - What is the difference between declaring an attribute in the
__init__()and declaring it outside__init__()e.g.self.pear =10
selfwill be an instance ofPar.self.__dict__is a dict which holds attributes ofself. When you sayan entry in the dict is created:
self.__dict__will include{'fruit':chip}.When you say
you are declaring that
Parmust be passed two values,chipandfig. (Theselfinstance will be passed to__init__for you.)So inside the
__init__, the local variables (not attributes!)chipandfigare known.self.fruit = chipis creating an attributefruitwith valuechip.For example,
yields
Note that to access the attributes you would normally use, for example,
par.fruitrather thanpar.__dict__['fruit']. I showpar.__dict__above only to give you a picture of what is going on behind the scenes.