环Python鳕鱼

2024-10-02 12:23:24 发布

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

self.textboxAnswer1.resize(100,50)
self.textboxAnswer2.resize(100,50)
self.textboxAnswer3.resize(100,50)
self.textboxAnswer4.resize(100,50)
self.textboxAnswer5.resize(100,50)
self.textboxAnswer6.resize(100,50)

有没有办法把这段代码放到一个循环中,变得更有效率,似乎很重复

使用python


Tags: 代码self办法resize有效率textboxanswer6textboxanswer2textboxanswer1
3条回答

您可以通过getattr访问类属性:

for i in range(6):
    getattr(self, 'textboxAnswer{}'.format(i)).resize(100,50)

希望这有帮助

textboxAnswer放在一个循环中,然后在它上面循环:

textboxes = # Add all the textboxes into a list here

for tBox in textboxes:
    tBox.resize(100,50)

它实际上取决于对象的形式,但在这种情况下(假设我不能出于任何原因修改对象),实际上可以使用__dict__和正则表达式:

import re

class T:
  def __init__(self):
    self.option1 = "1"
    self.option2 = "2"
    self.notthis = 3

  def test(self):
    for k in self.__dict__:
      if re.compile("option").match(k):  # selects only the attributes that start with "option"
        print(self.__dict__[k])  

t = T()
t.test()

它打印:

1
2

这是丑陋和低效,但做它的工作如果可以更改属性在对象中的存储方式(使用列表、元组或任何其他集合),请按照这种方式操作

适用于您的情况(请记住导入re):

for k in self.__dict__:
  if re.compile("textboxAnswer").match(k):
    self.__dict__[k].resize(100, 50)

相关问题 更多 >

    热门问题