F
F
FunnyJingle2016-03-10 18:56:03
Python
FunnyJingle, 2016-03-10 18:56:03

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)

How to create a function that would accept instances as input, from which it would pull out attributes, something like this:
def foo(ekz1, ekz2)
    return ekz1.attr1 * ekz.attr2

It is fundamentally important to declare a function that will have exactly instances of the class as input.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2016-03-11
@FunnyJingle

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)

So:
def foo(ekz1, ekz2):
    print(getattr(ekz1, "attr1"), getattr(ekz2, "attr2"))

However, if you want to track that the correct objects are passed to the function, it is better to use the hasattr method for this:
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])

X
xozzslip, 2016-03-10
@xozzslip

Python is a dynamically typed language ( wiki article on dynamic typing). So you can't declare a function whose input must be an instance of the class, you just have to type-test the argument inside the function ( a stackoverflow question on how to do this).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question