setevoy
setevoy

Reputation: 4662

Variable inherit to class from parent

Let's take main script with:

#!/usr/bin/env python

import cl1
import cl2

A = cl1.First()
A.one()

B = cl2.Second()
B.two()

print('\nRep from First class: %sRep from Second class: %s\n' % (A.rep1, B.rep2))

First class file is:

class First:

    def one(self):

        self.rep1 = 'Rep1.\n'

And Second class file contains:

from cl1 import First

class Second(First):

    def two(self):
        self.rep2 = 'Rep2'

How can I access variable named rep1 in class First from class Second?

I mean - something like:

from cl1 import First

class Second(First):

    def two(self):
        self.rep2 = 'Rep2'
        self.l = First()
        self.l.one()
        print('From First: %s' % self.l.rep1)

This will work - but I just again create First class object, thus - this is not inheritance:

$ ./main.py
From First: Rep1.


Rep from First class: Rep1.
Rep from Second class: Rep2

I'd like to use something like:

from cl1 import First

class Second(First):

    def two(self):
        self.rep2 = 'Rep2'
        self.rep1 = First.rep1
        print('From Second: %sFrom First: %s' % (self.rep2, self.rep1)

Python 2.7

P.S. I tried "play" with super(Second, self) and so on - but unsuccessful.

Upvotes: 0

Views: 46

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

What happens is that rep1 won't exist at least you first the method one(). You can do this:

class First:
    def __init__(self):
        self.one()
    def one(self):
        self.rep1 = 'Rep1.\n'

class Second(First):
    def two(self):
        self.rep2 = 'Rep2'
        self.rep1 = self.rep1
        print('From Second: %sFrom First: %s' % (self.rep2, self.rep1))

You can simply access to rep1 as if it were defined in the Second class because of inheritance.

Upvotes: 1

Tom Hunt
Tom Hunt

Reputation: 958

You don't need to do anything special. Just accessing self.rep1 from within a method of Second will give you the value. Of course, the value still needs to be set in that specific object, so if you have ob = Second(), you first have to call ob.one().

You could try something like:

def Second(First):
    def two(self):
        self.one()
        self.rep2 = 'Rep2'
        print(self.rep1, self.rep2) # this will access the value set by one()

Upvotes: 1

Related Questions