1

I have a class like the one given below:

class Someclass(object):
    def __init__(self, n1=5, n2=12):
        self.n1 = n1
        self.n2 = n2

I will like to use the arguments of __init__ from the aforementioned class in a function which I am defining in the following manner:

def Search(model: Someclass):
    n11 = 10
    n22 = 20
    print( type(model.__init__), type(model) )
    # I want to multiply self.n1 with n11 , and self.n2 with n22 using this function.


Search(Someclass)
>> <class 'function'> <class 'type'>

How can I access elements in __init__ constructor in Someclass inside Search?

user10853036
  • 125
  • 1
  • 8

1 Answers1

3

They are properties on the class-instance. If isinstance(m, Someclass) you can simply use m.n1 and m.n2:

class Someclass(object):
    def __init__(self, n1=5, n2=12):
        self.n1 = n1
        self.n2 = n2

def Search(model: Someclass):
    n11 = 10
    n22 = 20

    # Like So:
    mul = model.n1 * model.n2

    print( type(model.__init__), type(model) , mul)


Search(Someclass(5,10))

Output:

<class 'method'> <class '__main__.Someclass'> 50

This works in this case because the parameters are stored as instance variables at/on your instance - it would not work on params that do not get stored:

class Forgetful():
    def __init_(self,p1=2,p2=3,p3=4):
        print(p1,p2,p3)   # only consumed, not stored

f = Forgetful()   # prints "2 3 4" but does not store, values no longer retrievable

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • The documentation uses _instance variable_ whereasthe linked SO post uses _instance attribute_ - they are used synonymly for the same thing. – Patrick Artner Apr 18 '19 at 05:59