Python Forum

Full Version: How can classes access each other Functions and Variables at the same time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can classes access each other Functions and Variables at the same time? I know you have to use object and self with _init__
I was able to access Class A from Class B but I couldn't access both at the same time!!
For example:

Class A:
Var A1
Var A2
function A1
function A2
function A3
print any member in Class B

Class B:
Var B1
Var B2
function B1
function B2
function B3
print any member in Class A
you instantiate Class A from class B (in class B) or the other way around.
This is assuming different files for each class, names A.py and B.py
using code like (in class B):
import A

class B:
    def __init__(self):
        class_a = A() # Creates instance of A  named a
        class_a.A1() # Executes method A1 of class A
class A(object):

  m = 1

  def __init__(self, x):
    self.n = x + 2

class B(object):

  o = 3

  def __init__(self, x):
    self.p = x + 4

c = A(5)
d = B(6)
Output:
>>> A.m 1 >>> c.n 7 >>> B.o 3 >>> d.p 10
Thank you ichabod801,

class A(object):

m = 1

def __init__(self, x):
self.n = x + 2
Using c = A(5) d = B(6) in class A doesn't work, 'B' is not defined
class B(object):

o = 3

def __init__(self, x):
self.p = x + 4

c = A(5)
d = B(6)
Please use python and output tags when posting code and results. Here are instructions on how to do it.