Answer the question
In order to leave comments, you need to log in
How to pass class instance attributes to a function definition?
Hello, this question is from a beginner.
Let there be two classes and their instances.
class C1:
def __init__(self, value1):
self.attr1 = value1
class C2:
def __init__(self, value2):
self.attr2 = value2
inst1 = C1(val)
inst2 = C2(val)
def foo(ekz1, ekz2)
return ekz1.attr1 * ekz.attr2
Answer the question
In order to leave comments, you need to log in
ekz1.attr1 and getattr(ekz1, "attr1") are equivalent. Accordingly, in the function you can write anything you like:
And so:
def foo(ekz1, ekz2):
print(ekz1.attr1, ekz2.attr2)
def foo(ekz1, ekz2):
print(getattr(ekz1, "attr1"), getattr(ekz2, "attr2"))
class C1:
def __init__(self, value1):
self.attr1 = value1
class C2:
def __init__(self, value2):
self.attr2 = value2
def func(ekz1, ekz2):
if not hasattr(ekz1, "attr1"):
print("{0} has no attr1".format(type(ekz1)))
return
if not hasattr(ekz2, "attr2"):
print("{0} has no attr2".format(type(ekz2)))
return
print(ekz1.attr1, ekz2.attr2)
inst1 = C1(10)
inst2 = C2(11)
func(inst1, inst2)
func(inst1, [1, 2, 3])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question