python - 如何从 __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__
构造函数中的元素?Someclass
Search
解决方案
它们是类实例的属性。如果isinstance(m, Someclass)
您可以简单地使用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))
输出:
<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
独库:
官方文档:类和实例变量
在Python 类成员中阅读有关类属性/实例属性的更多信息
推荐阅读
- azure-service-fabric - Azure 服务结构 - 应用程序和服务类型
- javascript - react-native : 使用 setState 更新对象的值
- codeigniter - 如何使用循环 for(不是 foreach)打印/回显 result_array CodeIgniter
- php - 如何使用 phalcon 从供应商文件夹加载 css
- node.js - 板子用node.js实现重定向错误
- fonts - 设计字体时是否需要添加 U+FEFF (BOM) 字符
- c - 共享内存未同步更新
- php - 几秒钟的延迟 apache 响应
- javascript - 我一直试图让我的导航栏在滚动时固定在顶部。但它仍然固定在中间
- python - 我的自定义宏在我的电脑上工作,但在目标电脑上崩溃