【问题标题】:How to access elements from __init__ constructor如何从 __init__ 构造函数访问元素
【发布时间】:2019-04-18 05:41:12
【问题描述】:

我有一个类似于下面给出的课程:

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

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

【问题讨论】:

    标签: python class


    【解决方案1】:

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

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

    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
    

    独库:

    【讨论】:

    • 文档使用 instance variable 而链接的 SO 帖子使用 instance attribute - 它们与同一事物同义。
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2018-06-23
    • 2021-09-04
    • 2012-02-17
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多