Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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_File_Class - Fatal编程技术网

Python在类中执行函数

Python在类中执行函数,python,file,class,Python,File,Class,我很难理解如何有效地使用类。我已经写了一个程序,我希望计算一个短语或单词在.txt文件中出现的次数 我不太确定如何正确调用该函数,如有任何帮助,将不胜感激 谢谢 class WordCounter: def The_Count(self): print "Counting words..." txt_doc = open("file") for line in txt_doc: if "word"

我很难理解如何有效地使用类。我已经写了一个程序,我希望计算一个短语或单词在.txt文件中出现的次数

我不太确定如何正确调用该函数,如有任何帮助,将不胜感激

谢谢

class WordCounter:
    def The_Count(self):  
        print "Counting words..."       
        txt_doc = open("file")

        for line in txt_doc:
            if "word" in txt_doc:
                word_freq = word_freq + 1
                return word_freq

        print "Frequency of word: %s" % word_freq

要调用类中的方法,首先必须创建该类的实例:

c = WordCounter()
然后在该实例上调用该方法:

c.TheCount()

然而,在这种情况下,您并不真正需要类;这可能只是一个顶级函数。当您希望每个对象都有自己的内部状态时,类最有用。

要调用类中的方法,首先必须创建该类的实例:

c = WordCounter()
然后在该实例上调用该方法:

c.TheCount()

然而,在这种情况下,您并不真正需要类;这可能只是一个顶级函数。当您希望每个对象都有自己的内部状态时,类是最有用的。

这里有几个问题,您发布的代码不是正确的python。类方法应将对self的引用作为参数:

def The_Count(self):
如果没有要计数的单词,则需要初始化单词\u freq:

word_freq = 0
正如其他人提到的,您可以通过以下方式调用函数:

counter = WordCounter()
print(counter.The_Count())

在类中封装这些类型的无状态函数并不是真正惯用的python,就像在Java或其他语言中所做的那样。我将把这个函数分离成一个模块,让调用类处理文件I/O等。

这里有几个问题,您发布的代码不是正确的python。类方法应将对self的引用作为参数:

def The_Count(self):
如果没有要计数的单词,则需要初始化单词\u freq:

word_freq = 0
正如其他人提到的,您可以通过以下方式调用函数:

counter = WordCounter()
print(counter.The_Count())

在类中封装这些类型的无状态函数并不是真正惯用的python,就像在Java或其他语言中所做的那样。我将把这个函数分离成一个模块,并让调用类处理文件I/O等。

使用类与您在这里尝试的有点不同。更多地考虑在代码中保存变量和对象状态。为了完成您的任务,以下类似的方法将起作用:

class CountObject(object):
    """Instance of CountObject for measuring file lengths"""
    def __init__(self, filename):
        self.filename = filename
    def getcount(self, word):
        count = 0
        infile = open(self.filename,'r')
        for line in infile.readlines():
            x = line.count(word)
            count = count + x
        return count

mycounter = CountObject('C:\list.txt')
print 'The occcurence of awesome is %s' %(str(mycounter.getcount('in')))

使用类与您在这里尝试的有点不同。更多地考虑在代码中保存变量和对象状态。为了完成您的任务,以下类似的方法将起作用:

class CountObject(object):
    """Instance of CountObject for measuring file lengths"""
    def __init__(self, filename):
        self.filename = filename
    def getcount(self, word):
        count = 0
        infile = open(self.filename,'r')
        for line in infile.readlines():
            x = line.count(word)
            count = count + x
        return count

mycounter = CountObject('C:\list.txt')
print 'The occcurence of awesome is %s' %(str(mycounter.getcount('in')))

首先,为了在名称上达成一致,类中的函数被称为该类的方法

在您的示例中,您的方法执行计算单词出现次数的操作,因此为了更清楚,您可以简单地调用您的方法count。还请注意,在Python中,方法名以小写开头是一个很好的选择

此外,使用所谓的类也是一种很好的做法,这些类只是从对象继承的类

最后,在Python中,一个方法需要至少有一个参数,称为self,应该是类的实例

因此,如果我们应用这些更改,我们会得到如下结果:

class WordCounter(object):

    def count(self):  
        print "Counting words..."
    
        # Rest of your code
        # ...
class WordCounter(object):

    def __init__(self, txt_doc):
        self.word_file = txt_doc

    def count(self):
        print "Counting words..."       

        for line in self.txt_doc:
            # Rest of your code
            # ...
            
with open(filename) as f:
    word_counter = WordCounter(f)
    word_counter.count()
   
既然您的类有了一个方法,您首先需要创建类的实例,然后才能对其调用该方法。因此,要在Python中创建类Foo的实例,只需调用Foo即可。一旦有了实例,就可以调用方法。以你为例

# Create an instance of your class and save it in a variable
my_word_counter = WordCounter()
# Call your method on the instance you have just created
my_word_counter.count()
请注意,您不需要为self传入参数,因为self的值为word\u counter,即它调用WordCounter.countmy\u word\u counter

关于OO的一点注记 其他人已经注意到,您的示例在Python中并没有很好地使用类。OO类旨在将行为、实例方法以及它们与实例属性交互的数据放在一起。您的示例很简单,没有与类关联的真实内部数据。一个很好的警告可能是,你从来没有在你的方法中使用self

对于与某些特定数据无关的行为,Python为您提供了编写模块级函数的灵活性——相反,Java强制您将所有内容都放在类中

正如其他人所建议的,为了使您的示例更加面向对象,您可以将文件名作为参数传递给_init_uu,并将其另存为self.filename。也许更好的方法是让您的WordCounter期望一个类似文件的对象,这样它就不必负责打开/关闭文件本身。比如:

class WordCounter(object):

    def count(self):  
        print "Counting words..."
    
        # Rest of your code
        # ...
class WordCounter(object):

    def __init__(self, txt_doc):
        self.word_file = txt_doc

    def count(self):
        print "Counting words..."       

        for line in self.txt_doc:
            # Rest of your code
            # ...
            
with open(filename) as f:
    word_counter = WordCounter(f)
    word_counter.count()
   

最后,如果您想了解Python中类的更多详细信息,最好的信息来源始终是。

首先,就名称而言,类中的函数称为该类的方法

在您的示例中,您的方法执行计算单词出现次数的操作,因此为了更清楚,您可以简单地调用您的方法count。还请注意,在Python中,方法名以小写开头是一个很好的选择

而且,这是一个很好的练习 ce使用所谓的类,这些类只是从对象继承的类

最后,在Python中,一个方法需要至少有一个参数,称为self,应该是类的实例

因此,如果我们应用这些更改,我们会得到如下结果:

class WordCounter(object):

    def count(self):  
        print "Counting words..."
    
        # Rest of your code
        # ...
class WordCounter(object):

    def __init__(self, txt_doc):
        self.word_file = txt_doc

    def count(self):
        print "Counting words..."       

        for line in self.txt_doc:
            # Rest of your code
            # ...
            
with open(filename) as f:
    word_counter = WordCounter(f)
    word_counter.count()
   
既然您的类有了一个方法,您首先需要创建类的实例,然后才能对其调用该方法。因此,要在Python中创建类Foo的实例,只需调用Foo即可。一旦有了实例,就可以调用方法。以你为例

# Create an instance of your class and save it in a variable
my_word_counter = WordCounter()
# Call your method on the instance you have just created
my_word_counter.count()
请注意,您不需要为self传入参数,因为self的值为word\u counter,即它调用WordCounter.countmy\u word\u counter

关于OO的一点注记 其他人已经注意到,您的示例在Python中并没有很好地使用类。OO类旨在将行为、实例方法以及它们与实例属性交互的数据放在一起。您的示例很简单,没有与类关联的真实内部数据。一个很好的警告可能是,你从来没有在你的方法中使用self

对于与某些特定数据无关的行为,Python为您提供了编写模块级函数的灵活性——相反,Java强制您将所有内容都放在类中

正如其他人所建议的,为了使您的示例更加面向对象,您可以将文件名作为参数传递给_init_uu,并将其另存为self.filename。也许更好的方法是让您的WordCounter期望一个类似文件的对象,这样它就不必负责打开/关闭文件本身。比如:

class WordCounter(object):

    def count(self):  
        print "Counting words..."
    
        # Rest of your code
        # ...
class WordCounter(object):

    def __init__(self, txt_doc):
        self.word_file = txt_doc

    def count(self):
        print "Counting words..."       

        for line in self.txt_doc:
            # Rest of your code
            # ...
            
with open(filename) as f:
    word_counter = WordCounter(f)
    word_counter.count()
   

最后,如果您想了解Python中类的更多详细信息,最好的信息来源始终是。

对于这样一个小程序,可能不需要使用类。您可以简单地定义函数,然后调用它

但是,如果要实现类设计,可以在类定义之后使用:

if __name__ == "__main__":

wc = WordCounter() #create instance
wc.TheCount() #call method

如果您以后想进一步扩展类的功能,使用类设计可以使用更好的设计原则,同时提高代码的可读性/灵活性。

对于这样一个小程序,可能不需要使用类。您可以简单地定义函数,然后调用它

但是,如果要实现类设计,可以在类定义之后使用:

if __name__ == "__main__":

wc = WordCounter() #create instance
wc.TheCount() #call method

如果您以后想进一步扩展类的功能,使用类设计将使用更好的设计原则,同时提高代码的可读性/灵活性。

在这种情况下,您必须将代码更改为:

class WordCounter:
    def CountWords(self):
        # For functions inside classes, the first parameter must always be `self`
        # I'm sure there are exceptions to that rule, but none you should worry about
        # right now.
        print "Counting words..."          
        txt_doc = open("file")   
        word_freq = 0

        for line in txt_doc:   
            if "word" in line:   # I'm assuming you mean to use 'line' instead of 'txt_doc'
                word_freq += 1   
                # count all the words first before returning it

        txt_doc.close()          # Always close files after you open them.  
                                 # (also, consider learning about the 'with' keyword)

        # Either print the frequency
        print "Frequency of word: %s" % word_freq 
        # ...or return it.
        return word_freq
…那么,如果要叫它,你会

>>> foo = WordCounter()  # create an instance of the class
>>> foo.CountWords()     # run the function
正如其他海报所指出的,这并不是最有效地利用课堂。如果您将其设置为顶级函数,并将其更改为:

def CountWords(filename, word):
    with open(filename) as txt_doc:
        word_freq = 0
        for line in txt_doc:
            if word in line:
                word_freq += 1
    return word_freq
…并这样称呼它:

>>> output = CountWords("file.txt", "cat")
>>> print "Frequency of word: %s" % output
39
如果你有下面这样的东西,使用一个类会更有意义,你有一堆变量和函数都与一个概念性的“对象”相关:

类文件统计: def initself,文件名: self.filename=文件名

def CountWords(self, word):
    pass   # Add code here...

def CountNumberOfLetters(self):
    pass

def AverageLineLength(self):
    pass

# ...etc.

在这种情况下,您必须将代码更改为:

class WordCounter:
    def CountWords(self):
        # For functions inside classes, the first parameter must always be `self`
        # I'm sure there are exceptions to that rule, but none you should worry about
        # right now.
        print "Counting words..."          
        txt_doc = open("file")   
        word_freq = 0

        for line in txt_doc:   
            if "word" in line:   # I'm assuming you mean to use 'line' instead of 'txt_doc'
                word_freq += 1   
                # count all the words first before returning it

        txt_doc.close()          # Always close files after you open them.  
                                 # (also, consider learning about the 'with' keyword)

        # Either print the frequency
        print "Frequency of word: %s" % word_freq 
        # ...or return it.
        return word_freq
…那么,如果要叫它,你会

>>> foo = WordCounter()  # create an instance of the class
>>> foo.CountWords()     # run the function
正如其他海报所指出的,这并不是最有效地利用课堂。如果您将其设置为顶级函数,并将其更改为:

def CountWords(filename, word):
    with open(filename) as txt_doc:
        word_freq = 0
        for line in txt_doc:
            if word in line:
                word_freq += 1
    return word_freq
…并这样称呼它:

>>> output = CountWords("file.txt", "cat")
>>> print "Frequency of word: %s" % output
39
如果你有下面这样的东西,使用一个类会更有意义,你有一堆变量和函数都与一个概念性的“对象”相关:

类文件统计: def initself,文件名: self.filename=文件名

def CountWords(self, word):
    pass   # Add code here...

def CountNumberOfLetters(self):
    pass

def AverageLineLength(self):
    pass

# ...etc.

即使使用正确的代码,这也不是类的有效使用。def the_Countself:不要忘记包含类引用。即使使用正确的代码,这也不是类的有效使用。def the_Countself:不要忘记包含类引用。请注意,c.TheCount仍然会在此处引发异常,参数数目错误,计数中没有自我定义:。为了让它起作用,用@staticmethod来修饰计数器。自我在参数中实际做了什么?@Behzad:在你的例子中,什么都没有。因此,我的注释位于顶部。@Behzad-self是一个常规名称,它表示这个类对象。在上面的示例中,对象c将作为self传入。这有意义吗?请注意,c.TheCount仍然会在这里引发一个异常错误的参数数,count中的def中没有self:。为了让它起作用,用@staticmethod来修饰计数器。自我在参数中实际做了什么?@Behzad:在你的例子中,什么都没有。因此,我的注释位于顶部。@Behzad-self是一个常规名称,它表示这个类对象。在上面的示例中,对象c将作为self传入。这有意义吗?