[英]How to define a callable object into another python class
我已经定义了一个 Python 类。 我正在尝试将该结果对象放入另一个类中。 直到现在我都无法做到这一点,而我已经尝试通过互联网阅读了很多。 有没有人可以帮助我?
这个想法是首先堆叠来自图层定义的数组结果。
谢谢你的时间。
class Lit_dim():
num_units = 0 #class variables #Class variable to share with all instances
"""
Create a new layer grid for the BHE simulation model
"""
def __init__(self, x, y, z): #Constructor
"""
Definition of variables for grid creation with the layer definition
"""
self.x = x
self.y = y #Instance variables shared to each instance
self.z = z
self.units =[] #Creating the units list to an specific unit
Lit_dim.num_units += 1
def unit_index(self, unit_index):
self.unit_index = unit_index
self.layer = np.full((self.x, self.y), self.unit_index)
self.layer = np.repeat(self.layer, self.z, axis=0)
# return (self.layer)
def displayCount(self):
print ("Total number of units created: ", Lit_dim.num_units)
背后的想法是将这个先前类中的对象使用到一个新类中。 但是,当我尝试对该对象执行某些操作时,它告诉我该对象不可调用。
class model_creation(Lit_dim):
def __init__(self):
print ("Test")
unit_add = Lit_dim()
print (unit_add)
如果您的想法是将上一个类中的对象用于一个新类,您只需调用 Lit_dim,而不将它作为参数传递。
class Lit_dim():
num_units = 0 #class variables #Class variable to share with all instances
"""
Create a new layer grid for the BHE simulation model
"""
def __init__(self, x, y, z): #Constructor
"""
Definition of variables for grid creation with the layer definition
"""
self.x = x
self.y = y #Instance variables shared to each instance
self.z = z
self.units =[] #Creating the units list to an specific unit
Lit_dim.num_units += 1
def unit_index(self, unit_index):
self.unit_index = unit_index
self.layer = np.full((self.x, self.y), self.unit_index)
self.layer = np.repeat(self.layer, self.z, axis=0)
# return (self.layer)
def displayCount(self):
print ("Total number of units created: ", Lit_dim.num_units)
class model_creation():
def __init__(self):
print ("Test")
unit_add = Lit_dim(1, 2, 3)
print (unit_add, unit_add.x, unit_add.y, unit_add.z)
def main():
model_creation()
main()
输出:
Test
<__main__.Lit_dim object at 0x10a59f198> 1 2 3
您需要指定要访问的变量:
def __init__(self):
print ("Test")
unit_add = Lit_dim()
print (unit_add.<variable name here>)
你首先像你一样从一个类中创建一个对象:
unit_add = Lit_dim()
但是随后您需要访问该对象中的特定变量
print(unit_add.<variable name here>)
您必须在类内部定义调用它的对象时会发生什么。
def __repr__(self):
return "whatever atributes you wish"
打印有一个特殊情况。
def __str__(self):
return "Print this"
>>>> t = Lit_Dim()
>>>> t
whatever atributes you wish
>>>> print(t)
Print this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.