python - python对象的访问名称

标签 python oop names

我制作了一个使用电热丝的类(class):

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]

最佳答案

就这样去做,没有重复:

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)
]

要回答您的问题,不,对象不能访问它们被赋予的名称。

关于python - python对象的访问名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102755/

相关文章:

python - 如何在 Keras 中设置自适应学习率

python - 抓取谷歌搜索片段结果

c - C中相同结构的两个名称

.net - .NET Web 服务客户端是否支持在备用主题名称中使用 IP 的 SSL 证书

javascript - 如何在类构造函数中使用原型(prototype)方法

r - 管道 R 代码中的 setnames

python - 跟踪和显示已执行代码的百分比

python - 如果其他目标单词在原始目标的 10 个单词之内,则匹配目标单词的正则表达式

Java Swing Frame 导航到另一个 Frame

python - 将值传递给类