A
A
Alexander Movchan2015-01-24 20:06:10
Python
Alexander Movchan, 2015-01-24 20:06:10

How to inherit base class attributes in Python?

There is this code:

class BaseImage:

    def __init__(self, width = 1920, height = 1080, bytespp = 3):
        self.__width = width
        self.__height = height
        self.__bytespp = bytespp
        self.__image = bytearray(self.__width * self.__height * self.__bytespp)


    def __getitem__(self, coordinate):
        shift = (coordinate[0] + self.__width * coordinate[1]) * self.__bytespp
        return self.__image[shift : shift + self.__bytespp]
    

    def __setitem__(self, coordinate, color):
        if len(color) != self.__bytespp:
            raise BadColorError
        shift= (coordinate[0] + self.__width * coordinate[1]) * self.__bytespp
        self.__image[shift : shift + self.__bytespp] = color


class TGAImage(BaseImage):

    def __init__(self, width = 1920, height = 1080, bytespp = 3):
        BaseImage(width, height, bytespp)


    def write(self, target):
        out = open(target, 'bw')
        header_area = (
            b'\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            + bytes([super.__width // 256, super().__width % 256]) 
            + bytes([super().__height // 256, super().__height % 256]) 
            + bytes([super().__bytespp << 3]) 
            + b'\x20')
        dev_area = b'\x00\x00\x00\x00'
        ext_area = b'\x00\x00\x00\x00'
        foot_area = b'TRUEVISION-XFILE.\0'
        out.write(header_area)
        out.write(super().__image)
        out.write(dev_area)
        out.write(ext_area)
        out.write(foot_area)
        out.close()

Throws an error when calling the __setitem__ method on a TGAImage object.
>>> image = ImageIO.TGAImage()
>>> for x in range(1080):
...     image[x, x] = b'\xff\x00\x00'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/alexander/Codding/Render/Render/ImageIO.py", line 25, in __setitem__
    if len(color) != self.__bytespp:
AttributeError: 'TGAImage' object has no attribute '_BaseImage__bytespp'

As far as I understood, it does not find the __bytespp attribute of the TGAImage object.
How to inherit it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yttrium, 2015-01-24
@Alexander1705

If attributes are supposed to be inherited, they should not be named starting with a double underscore, as double underscore triggers the name mangling mechanism

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question