Nobi
Nobi

Reputation: 1109

Subclass calling its superclass method

please I have a class WN that is a subclass of N. N has a method create_nl() that appends the keys and values in the pos dictionary to two empty lists nl and nv. My question is how can I write a method in the subclass to call the create_nl() method in class N such that A and B in wr(), gets assigned random values from the nl list in the superclass method create_nl().I have written a code for that below but it generates an error. Thanks

import random as rand

pos = {1:(0, 0.1), 2:(0, 0.), 3:(0, 0.3), 4:(0, 0.4), 5:(0, 0.5), 6:(0, 0.6) }

class N(object):

    def __init__(self, name):
        self.name = name

    def create_nl(self):
        nv = []
        nl = []
        for key, value in pos.iteritems():
            nl.append(key)
            nv.append(value)
        return nl

nn = N("CT")
nn.create_nl()


class WN(N):

def n(self):
    return super(WN, self).create_nl()

def wr(self):

    count = 0

    while count < 1:

        A = int(rand.choice(self.n))
        B = int(rand.choice(self.n))

    count += 1

Upvotes: 0

Views: 57

Answers (1)

Blckknght
Blckknght

Reputation: 104702

You can call superclass methods directly on subclass instances. You only need to use super if you've overridden the method in the subclass and you want to access the superclass version instead of the override.

class WN(N):
    def wr(self):
        nl = self.create_nl() # calls superclass method, which we have not overridden

        A = random.choice(nl) # use the return value
        B = random.choice(nl)

Note that it's a bit strange to be using a method like create_nl to access global data, rather than instance data. Your random.choice calls could just as easily be done directly on pos directly!

Upvotes: 1

Related Questions