Yet another question about class property.

Dave Angel davea at ieee.org
Thu May 21 01:07:00 EDT 2009


Jim Qiu wrote:
> Thanks for you patience, Dave.
> Obviously i have not got used to the python philosophy.
>
> Following you guide, i implemented the following code, and you are
> absolutely right.
>
> #!/usr/bin/python
> #coding:utf-8
>
> class Parent(object):
>
> def __init__(self):
> pass
>
> def displayAttrOfSubClass(self):
> print self.attrFromChild
>
> class Child(Parent):
> def __init__(self):
> self.attrFromChild = 'Hi, Everyone, Java does this support this trick!'
>
>
> childObj = Child()
> childObj.displayAttrOfSubClass()
>
>
> Python can use in the parent class a variable only instantiated by a
> sub-class, is this a point of advance of technique of Python?
>
> Jim
>
>   
>
(You're top-posting.  Also, for some reason the indentation is not being 
preserved in your messages.  No problem here, but more complex code 
examples would be totally illegible.)

In Python, you don't have to declare an attribute before using it.  
Rather than getting a compile-time error, like C++ or Java, you get a 
runtime error if the attribute isn't present by the time you use it.

However, if somebody (anybody) else has already defined it (assigned a 
value to it), then you can go ahead and use that value.  It's a common 
pattern with abstract base classes, and it's useful because those 
classes are never meant to be directly instantiated.

In C++ abstract classes, you have to declare all the *methods* you use, 
but you don't have to define their implementation.  You can call these 
methods, even though they don't exist in the base class, because the 
derived class will be defining them before you can get control.  
However, C++ gives no way to do that for data.

The real advantage is not that you can define a data attribute in a 
child class, but that its type can be different in each child class, and 
the base class generally need not know.




More information about the Python-list mailing list