python对象的访问名

2024-05-14 03:47:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个关于加热电线的课程:

class Heating_wire:

    def __init__(self, ro, L,d,alpha):

        self.ro = ro
        self.L = L
        self.d = d
        self.alpha = alpha
        self.RT = [1]
        self.vector_T = [1]
    def get_R20(self):
        self.R_20 =  self.ro*self.L/(np.pi*(self.d/2)**2)

    def  calcular_RT(self,vector_temp):
        self.vector_T = vector_temp
        self.RT =  [self.R_20*(1 + temp*self.alpha) for temp in vector_temp ]
        return self.RT

实例化一些对象:

kantal = Heating_wire(1.45,0.25,0.3,4e-5)
nicromo = Heating_wire(1.18,0.25,0.3,0.0004)
ferroniquel = Heating_wire(0.86,0.25,0.3,9.3e-4)

wires = [kantal,nicromo,ferroniquel]

做了个阴谋:

leg = []
vector_temp = np.linspace(20,1000,1000)
for wire in sorted(wires):
    wire.get_R20()
    wire.get_RT(vector_temp)
    line, = plt.plot(wire.vector_T,wire.RT)
    leg.append(line)
plt.legend(leg,sorted(wires))

问题是我在图例中没有得到正确的名称,而是对对象的引用:

enter image description here

如果我添加name属性

def __init__(self,name, ro, L,d,alpha):
    self.name = name

我可以加上名字

leg = []

names= []
vector_temp = np.linspace(20,1000,1000)
for wire in sorted(wires):
    wire.get_R20()
    wire.get_RT(vector_temp)
    line, = plt.plot(wire.vector_T,wire.RT)
    leg.append(line)
    names.append(wire.name)
plt.legend(leg,names,loc='best') 

enter image description here

但我想知道是否有一种更简单的方法可以直接使用导线列表中的对象名称来解决这个问题:

kantal = Heating_wire(1.45,0.25,0.3,4e-5)
nicromo = Heating_wire(1.18,0.25,0.3,0.0004)
ferroniquel = Heating_wire(0.86,0.25,0.3,9.3e-4)

wires = [kantal,nicromo,ferroniquel]

Tags: nameselfalphagetrodeftempvector
1条回答
网友
1楼 · 发布于 2024-05-14 03:47:27

就这样做,没有重复:

wires = [
    Heating_wire("kantal", 1.45,0.25,0.3,4e-5),
    Heating_wire("nicromo", 1.18,0.25,0.3,0.0004),
    Heating_wire("ferroniquel", 0.86,0.25,0.3,9.3e-4)
]

要回答您的问题,不,对象不能访问给定的名称。你知道吗

相关问题 更多 >