开发者

How do I access base class variables through an instance of a child class in Python?

I wanted to know how to access to the super class’s variables with a object of child class If it makes any sense I add that some of the variables are defined in this __variable name way. Any time I want to access the variables with a child object. Python says the object with the type CHILE CLASS TYPE here is not defined. I wanted to know how I can solve this? I also want to add that t开发者_JS百科he super class is not explicitly defined and it is just imported from a module.

class AcuExcelSheet (  Worksheet  ):  ## super class which is imported from module 
    def __init__(self):
        Worksheet.__init__(self)

sheet = AcuExcelSheet()
for row_index in range(sheet.nrows):
        for col_index in range(sheet.ncols):
            print sheet.cell(row_index,col_index).value

for row_index in range(sheet.nrows): AttributeError: 'AcuExcelSheet' object has no attribute 'nrows'

I want to know about the syntax of this class variable’s call. Because I can see that attribute nrow has been defined in the constructor of Worksheet class.


Something is wrong, but not with the code you've shown. If Worksheet truly defines .nrows, then your AcuExcelSheet will have access to it. There are a few possibilities:

  1. Worksheet doesn't define nrows. You mention double-underscore names. Are you sure it isn't __nrows?
  2. Worksheet defines nrows, but only for some code paths, and your invocation of the constructor doesn't hit those code paths.


Forgive me if I'm misunderstanding something, but doesn't the child class automatically inherit the methods of the super class? See this for example:

>>> class A(object):
...     def __init__(self):
...             self.data = "GIMME TEH DATA"
... 
>>> a = A()
>>> a.data
'GIMME TEH DATA'
>>> class B(A):
...     pass
... 
>>> b = B()
>>> b.data
'GIMME TEH DATA'

So the superclass A's init method sets the data attribute. B is the child class, and an instance of B has automatically the same data attribute initialised.

What I mean to say from this is that this part seems entirely unnecessary to me:

def __init__(self):
    Worksheet.__init__(self)

(As for the rest I agree with the commenter that you'd need to either use introspection or find documentation to find out what attributes Worksheet has -- something along the lines of

>>> a = Worksheet()
>>> print dir(a)

.)


There's no separated base class instance dictionary in object instances. As line

Worksheet.__init__(self)

says objects of AcuExcelSheet are initialized by Worksheet class. All may you need - to access base class method, that was redefined, you can do it just by

super(AcuExcelSheet,self).method_name

expression. So if you can't find some attributes in child class instance, maybe it needs some additional initialization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜