【问题标题】:creating a class for the first time, and am having issues第一次创建课程,并且遇到问题
【发布时间】:2018-10-20 10:08:00
【问题描述】:

我不断收到 ma​​in.division 对象的绑定方法 division.common_divisor...错误。 我猜我应该只使用函数而不是类?

class division(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def divisor(self):
        div_list=[]
        i = 1
        while i<self.x:
            if self.x%i == 0:
                div_list.append(i)
            i+=1
        return div_list
    def common_divisor(self):
        sml1=divisor(self.x)
        sml2=divisor(self.y)
        common_lst=[]
        for i in sml1:
            for char in sml2:
                if i==char:
                    common_lst.append(i)
        return common_lst
check = division(10,20)
print (check.common_divisor)

【问题讨论】:

  • 那么问题到底是什么?

标签: python python-3.x


【解决方案1】:

您的代码中几乎没有错误:

1)

print (check.common_divisor)

这一行不打印调用common_divisor方法的结果,它只是打印方法而不调用它 - 你忘了添加()print(check.common_divisor())是正确的

2) 在您的 common_divisor 方法中,您调用了 divisor 函数,但它没有被定义。您尝试调用divisor 方法,我想:self.divisor() 会这样做

3) 在divisor 方法中,您使用self.x 而不是从common_divisor 方法传递的参数

4) 在您的代码中,您错过了一个数字除以第二个数字的情况:

while i < x:

不会返回数字作为自己的分隔符

固定代码:

class division(object):

    def __init__(self, x, y):
        self.x, self.y = x, y

    def divisors(self, x):
        div_list = []
        i = 1
        while i <= x:
            if x % i == 0:
                div_list.append(i)
            i += 1
        return div_list

    def common_divisor(self):
        sml1 = self.divisors(self.x)
        sml2 = self.divisors(self.y)
        common_lst = []
        for i in sml1:
            for char in sml2:
                if i == char:
                    common_lst.append(i)
        return common_lst

check = division(10, 20)
print(check.common_divisor())

输出:

[1, 2, 5, 10]

【讨论】:

    【解决方案2】:

    感谢@ingvar,我能够看到我做错了什么,这是最终的功能代码。 分类(对象): def init(self,x,y): 自我.x=x 自我.y=y def 除数X(自我): div_list=[] 我 = 1 当我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2022-12-18
      • 2011-09-18
      • 2020-04-25
      • 2021-06-14
      相关资源
      最近更新 更多