首页 > 解决方案 > 如何从 __init__ 构造函数访问元素

问题描述

我有一门课,如下所示:

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

我想__init__在我以下列方式定义的函数中使用上述类的参数:

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'>

如何访问内部__init__构造函数中的元素?SomeclassSearch

标签: pythonclass

解决方案


它们是类实例的属性。如果isinstance(m, Someclass)您可以简单地使用m.n1and 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))

输出:

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

这在这种情况下有效,因为参数作为实例变量存储在您的实例上/实例上 - 它不适用于未存储的参数:

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

独库:


推荐阅读