简体   繁体   中英

Modyfying parent class attribute in __init__

I would like to build object oriented model for file/strings converter. I managed to solved the issue using functional approach but it just beggs for OOP.

Here is the case:

My input data to convert is a list of common dictionaries but with different values (dump from CSV file).

I need to update value of data3 in class A which is hidden inside of a list ( fileHeader ) that is initialized within A's __init__ method.

class Common(object)
    def __init__(self, c):  # for now c will be a dictionary that we iterate over in external loop
        self.c = c

    def printdata(self, obj): # method used for printing (writting to a file in future)
        print ''.join(obj)

 class A(Common):   # creates file header
    def __init__(self, c):  #c is a dict
        self.c = c
        __data1 = 'data1'
        self.__data2 =  'data2'
        self.data3 = 'data3'
        self.fileHeader = [__data1, __data2, self.__data3] # contains data3 value that i want to modify in Class B

class B(A):  # creates file footer, need to use modified fileHeader value
    def __init__(self, c):
        A.__init__(self, c)     # gives me access to self.fileHeader
        ## magically change fileHeader's value updateing data3##
        data4 = 'data4' 
        data5 = 'data5'
        ....
        self.fileFooter = [data4, ''.join(self.fileHeader), data5]  # refering fileHeader here gives me original 'data3' value

Actual behaviour is that i get:
fileHeader = ['data1', 'data2', 'data3']
fileFooter = ['data4','data1', 'data2', 'data3', 'data5' ]

desired behaviour is to get modified data3='data3_modified' :
fileHeader - no changes
fileFooter = ['data4','data1', 'data2, 'data3_modified', 'data5' ]

note that i've ignored ''.join() result for readability

Attributes don't "belong" to a class in the hierarchy. They belong to the current object, which is an instance of B but inherits from A and Common; every attribute defined in code in those classes is directly available on A. This is the fundamental thing about subclassing.

So, you can just access self.data3 in your B.__init__ code, or anywhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM