简体   繁体   中英

Python 3.X: How do you call a function of a class to check for the characterisitics of an input string?

import re

class WordClasses:

    """A Class designed to regulate the certain characteristics of word choices made by users so that the adlib maintains
    a grammatical consistency and avoids sophomoric humor."""

    def noun(self, noun):

        self.noun = noun

        if not re.match("^[a-z]*$", noun):
            print("Error! Only letters a-z allowed!")
        elif len(noun) > 15:
            print("Error! Only 15 characters allowed!")

I have attempted to call the function in a test .py file:

Please enter noun to be used as a name: My name is Jeff

But receive the following error after issuing the input.

Traceback (most recent call last):
  File "C:/Users/jmatt/PythonPrograms/WordGame1/RestrictionTests.py", line 26, in <module>
    wordChoice = WordClasses.noun(input("Please enter noun to be used as a name: "))
TypeError: noun() missing 1 required positional argument: 'noun'

The code being called inside the test file:

wordChoice = WordClasses.noun(input("Please enter noun to be used as a name: "))
print(wordChoice)

I hope to create a few custom alibs and or grammar tests which will test for a passage's readability. And put it up against the parameters which can be called as part of the functions. their are seven other functions which borrow the same expectations and which are just the other types of classes. Prepositions, conjunctions, and determiners have word banks they test against though so any passage I write doesn't become nonsensical though. Any Advice is appreciated.

In your code,

wordChoice = WordClasses.noun(input("Please enter noun to be used as a name: "))

You are treating noun as a static function, which is not. So, the input string is filled for self rather than noun variable. Hence the error missing positional argument 'noun'

What you should be doing is create an instance and then call the function.

wc = WordClasses()
wc.noun(input("Please enter noun to be used as a name: "))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM