Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
面向对象python程序_Python_Oop - Fatal编程技术网

面向对象python程序

面向对象python程序,python,oop,Python,Oop,该程序将一个单词作为输入,并给出每个重复字符的出现次数和 输出该数字以及重复序列的单个字符 我不明白,为什么这不起作用。我得到这个错误: from collections import Counter class Runlength: def __init__(self): self.str = 0 def returner(self,str): self.str = str self.__str = ','.join(st

该程序将一个单词作为输入,并给出每个重复字符的出现次数和 输出该数字以及重复序列的单个字符

我不明白,为什么这不起作用。我得到这个错误:

from collections import Counter

class Runlength:
    def __init__(self):
        self.str = 0 

    def returner(self,str):
        self.str = str 
        self.__str = ','.join(str(n) for n in self.__str)
        self.__str = self.__str[::-1]
        self.__str = self.__str.replace(',', '')
        return self.__str
    def final(self,num):
        self.num = num 
        k = []
        c = Counter(self.num).most_common()
        for x in c:
        k += x     
        return k
math = Runlength() 

def Main():
a = "aabbcc"
b = math.returner(a)
c = math.final(b)
print(c)
Main()

问题在于,在
Main()
中,您没有访问全局变量(在
Main()
方法的范围之外)
math
变量。相反,尝试在
Main()函数中初始化
math

这让方法知道它应该使用全局
math
变量,而不是试图寻找不存在的局部变量

NameError: global name 'returner' is not defined
这应该行得通


但是我观察到,如果对象没有声明为全局对象,那么它甚至可以被访问。在上述场景中,他们对此有何解释?

我在您的代码中发现了以下错误:

def Main():
   math = Runlength() 
   a = "aabbcc"
   b = math.returner(a)
   c = math.final(b)
   print(c)
Main()
也许你的意思是:

self.__str = ','.join(str(n) for n in self.__str)
AttributeError: Runlength instance has no attribute '_Runlength__str'
并将returner()方法的输入参数选择为str_uunotstr,因为str--是python内置类型的名称,所以最好不要选择具有内置类型名称的变量名称。 因此,在这些更改之后,我得到了以下输出:

self.__str = ','.join(str(n) for n in self.str
所以,我的python版本是2.7.3,您所遇到的错误不会出现在我的python版本中。 您使用什么python版本编译代码?如果这个python3也很好用。那么试试下面的代码,它对我来说也很好用:

['a', 2, 'c', 2, 'b', 2]

此代码不会产生该错误。您当前的代码是什么?由于math未在函数作用域中声明,也未声明为“全局”,因此“Main()”不能引用“math”对象。No。如果要重新绑定名称,而不仅仅是访问名称,只需使用
global
from collections import Counter

class Runlength:
    def __init__(self):
        self.str = 0

    def returner(self,str_):
        self.string = str_
        self.__str = ','.join(str(n) for n in self.string)
        self.__str = self.__str[::-1]
        self.__str = self.__str.replace(',', '')
        return self.__str
    def final(self,num):
        self.num = num
        k = []
        c = Counter(self.num).most_common()
        for x in c:
            k += x
        return k
math = Runlength()

def Main():
    a = "aabbcc"
    b = math.returner(a)
    c = math.final(b)
    print(c)
Main()