Reputation: 5972
I have a python program with this structure:
import sys
class A:
def __init__(self):
...
def func(self, other, args):
z = something
n = B.start(z)
print n
def other_funcs(self, some, args):
...
class B:
def __init__(self):
self.start(z)
def start(self, z)
k = something
return k
if __name__ == '__main__'
A()
When I generate z
I want to give it to B class and then B returns k for me again.
But the error exists:
TypeError: unbound method start() must be called with B instance as first argument (got list instance instead)
Upvotes: 2
Views: 114
Reputation: 182
You can modify __init__
of class B
to take an argument which passes z
to it.
class B:
__init__(self, z): #Pass 'z' when you create an object a 'class B' in 'class A'
There are some problems with your code.
You need to understand what a constructor
is and when it gets called. You have
if __name__ == '__main__': # Fixed missing colon here
A()
This only calls the __init__
function of class A
.
You need to use something like
A().func() # Pass required arguments here
The proper way to use methods in classes is to create objects (however not required for class methods). In your class A
you have
n = B.start(z) # Line in func() of class A
This doesn't work.
You need to call B()
with required arguments for __init__
in class B
and not simply B
.
Example code passing message from class A
and printing it from class B
:
class foo:
def __init__(self):
self.var1 = "I'm from class A"
bar(self.var1)
class bar:
def __init__(self, var):
print(var)
if __name__ == '__main__':
foo()
Upvotes: 1
Reputation: 76297
IIUC, what you're looking for here is classmethod
.
The problem is that you don't have a a B
object, but rather just the B
class. You need a method of B
that takes a class, not an instance. Define start
like so:
@classmethod
def start(cls, z):
For example, this runs fine:
class A:
def func(self):
n = B.start(0)
class B:
@classmethod
def start(cls, z):
pass
if __name__ == '__main__':
A().func()
Upvotes: 2
Reputation: 59164
Alternatively you can initialize a B
object:
n = B().start(z)
However your __init__
method calls start
with argument z
which may not work as z
is not defined yet.
Upvotes: 2