Test/Class

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Fakhro
User
Beiträge: 21
Registriert: Mittwoch 13. März 2019, 13:44

Hi brauche dringend eure hilfe und zwar komme ich nicht mehr weiter

Hier erstelle ich eine class die ich testen möchte

Code: Alles auswählen

class AnonymousSurvey():
    """Collect anonymous ansers to a survey question."""

    def __init__(self, question):
        """Store a question, and prepare to store responses."""
        self.question = question
        self.responses = []

    def show_question(self):
        """Show the survey question"""
        print(question)

    def store_response(self, new_response):
        """Store a single response to the survey."""
        self.responses.append(new_response)

    def show_result(self):
        """Show all the responses that have been given."""
        print("Survey Results:")
        for response in responses:
            print('- ' + response)

Code: Alles auswählen

from survey import AnonymousSurvey

# Define a question, and make a survey.
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

# Show the question, and store responses to the question.
my_survey.show_question()
print("Enter 'q' at any time to quit. \n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_respons(response)

# Show the survey results.
print("\nThank you to everyone who participated in the survey !")
Hier weise ich ihr die werte hin zu und versuche sie ausführen aber es klappt nicht was ich garnicht verstehe Dies gibt er mir raus er eingeblich hätte question keine definition

Code: Alles auswählen

Traceback (most recent call last):
  File "C:\Users\mojo\AppData\Local\Programs\Python\Python37-32\language_survey.py", line 8, in <module>
    my_survey.show_question()
  File "C:\Users\mojo\AppData\Local\Programs\Python\Python37-32\survey.py", line 11, in show_question
    print(question)
NameError: name 'question' is not defined
Ich führe dies über die IDEL aus
Ich hoffe ihr könnt mir helfen
mfg fakhro
Benutzeravatar
__blackjack__
User
Beiträge: 13004
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Fakhro: Es gibt dort ja auch keine `question`. Wo sollte das denn definiert sein? Schau doch mal wo Du denkst das die Definition dafür steht und vergleiche was Du dort machst, und was Du dann in den anderen Methoden anders machst.
“Most people find the concept of programming obvious, but the doing impossible.” — Alan J. Perlis
Benutzeravatar
__blackjack__
User
Beiträge: 13004
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Fakhro: Weitere Anmerkungen:

Auf Modulebene sollte nur Code stehen der Konstanten, Funktionen, und Klassen definiert. Das Hauptprogramm steht üblicherweise in einer Funktion die `main()` heisst.

Die Klasse rechtfertigt kein eigenes Modul.

Der Name ist falsch – ein „Survey“ besteht aus mehr als einer Frage. Die Klasse modelliert also nur eine Frage eines „Survey“. Und wenn die Klasse dann richtig `Question` heisst, dann ist es komisch das die ein Attribut hat, das auch wieder `question` heisst. Das wäre dann eher `text`.

Der Docstring der Klasse beschreibt eine Tätigkeit, die Klasse ist aber keine Tätigkeit, sondern ein ”Ding”.

„Store a single response to the survey.“ ist irreführend, weil das so klingt als wenn da genau eine Antwort gespeichert wird. Da sollte „add“ im Methodennamen und im Docstring stehen. Dafür ist das `new_` bei `new_response` unnötig.

`show_result()` würde ich `show_responses()` nennen. Damit ist klar das nur die Antworten und nicht auch die Frage angezeigt wird. Wenn beides anzeigt würde, würde ich auch nur `show()` als Namen wählen. Beziehungsweise statt der Methode eine `__str__()`-Methode implementieren und das Objekt dann einfach mit `print()` ausgeben. Die Ausgabe „Survey Results:“ ist inhaltlich wieder falsch, weil das nur eine Frage ist, ein Surver aber aus mehr als einer Frage besteht.

Die meisten Doctsrings sind eigentlich alle für die Tonne. Wer die braucht, dem ist nicht mehr zu helfen, denn wenn jemand die Methodennamen nicht versteht, dann bringt auch ein Dosctring in dem noch mal fast wörtlich das gleiche steht, nichts.

Das gleiche gilt für die Kommentare im Hauptprogramm. Die braucht kein Mensch.

Wobei man den letzten Kommentar vielleicht durch Code ersetzen sollte der auch tatsächlich das tut was der Kommentar aussagt.

Was soll das `my_` bei `my_survey`? Gibt es auch `our_survey` oder `their_survey`?

Was den Entwurf angeht kann man überlegen ob Benutzerinteraktion in die Klasse gehört, denn im Moment hat man keine Trennung zwischen Programmlogik und Benutzerinteraktion.

Bei nur einer Frage ist auch die Klasse ein bisschen overkill. Da braucht man ja fast nicht einmal mehr als eine Funktion für dieses Programm.

Code: Alles auswählen

#!/usr/bin/env python3


class Question:
    """A question and answers."""

    def __init__(self, text):
        """Store a question text, and prepare to store responses."""
        self.text = text
        self.responses = list()

    def add_response(self, response):
        self.responses.append(response)

    def show_question(self):
        print(self.text)

    def show_responses(self):
        print('Responses:')
        for response in self.responses:
            print('-', response)


def main():
    survey = Question('What language did you first learn to speak?')

    survey.show_question()
    print("Enter 'q' at any time to quit.\n")
    while True:
        response = input('Language: ')
        if response == 'q':
            break
        survey.add_response(response)

    survey.show_responses()
    print('\nThank you to everyone who participated in the survey !')


if __name__ == '__main__':
    main()
“Most people find the concept of programming obvious, but the doing impossible.” — Alan J. Perlis
Benutzeravatar
__blackjack__
User
Beiträge: 13004
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Um den letzten Punkt noch mal zu illustrieren das ganze ohne die Klasse um die Häflte kürzer ohne das da wirklich irgendwas fehlen würde:

Code: Alles auswählen

#!/usr/bin/env python3


def main():
    responses = list()
    print('What language did you first learn to speak?')
    print("Enter 'q' at any time to quit.\n")
    while True:
        response = input('Language: ')
        if response == 'q':
            break
        responses.append(response)

    print('Responses:')
    for response in responses:
        print('-', response)
    
    print('\nThank you to everyone who participated in the survey !')


if __name__ == '__main__':
    main()
“Most people find the concept of programming obvious, but the doing impossible.” — Alan J. Perlis
Fakhro
User
Beiträge: 21
Registriert: Mittwoch 13. März 2019, 13:44

Immer mit der ruhe dass man dies alles in eine funktion schreiben dass weiß ich danke dir für deine mühe.
warum mich grad der code so neugierig macht ist weil es im buch "Python Crash Course" Funktioniert aber bei mir nicht
Text vom buch:
A Class to Test
Testing a class is similar to testing a function—much of your work involves
testing the behavior of the methods in the class. But there are a few differences, so let’s write a class to test. Consider a class that helps administer
anonymous surveys:

Code: Alles auswählen

class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
def __init__(self, question):
"""Store a question, and prepare to store responses."""
self.question = question
self.responses = []
def show_question(self):
"""Show the survey question."""
print(question)
def store_response(self, new_response):
"""Store a single response to the survey."""
self.responses.append(new_response)
def show_results(self):
"""Show all the responses that have been given."""
print("Survey results:")
for response in responses:
print('- ' + response)
This class starts with a survey question that you provide uand includes
an empty list to store responses. The class has methods to print the survey
question v, add a new response to the response list w, and print all the
responses stored in the list x. To create an instance from this class, all you
224 Chapter 11
have to provide is a question. Once you have an instance representing a particular survey, you display the survey question with show_question(), store a
response using store_response(), and show results with show_results().
To show that the AnonymousSurveyclass works, let’s write a program that
uses the class:

Code: Alles auswählen

language_  from survey import AnonymousSurvey
survey.py
# Define a question, and make a survey.
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# Show the question, and store responses to the question.
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
# Show the survey results.
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
OUTPUT OUTPUT OUTPUT
This program defines a question ("What language did you first learn
to speak?") and creates an AnonymousSurveyobject with that question. The
program calls show_question()to display the question and then prompts for
responses. Each response is stored as it is received. When all responses have
been entered (the user inputs qto quit), show_results()prints the survey
results:
What language did you first learn to speak?
Enter 'q' at any time to quit.
Language: English
Language: Spanish
Language: English
Language: Mandarin
Language: q
Thank you to everyone who participated in the survey!
Survey results:
- English
- Spanish
- English
- Mandarin
Benutzeravatar
__blackjack__
User
Beiträge: 13004
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Fakhro: Dann solltest Du mal schauen ob es zu dem Buch eine Webseite mit Errata gibt, denn der Code ist halt falsch/defekt und kann so nicht laufen ohne das man ihn vorher repariert.
“Most people find the concept of programming obvious, but the doing impossible.” — Alan J. Perlis
Fakhro
User
Beiträge: 21
Registriert: Mittwoch 13. März 2019, 13:44

Dass hat mich ja gewundert deswegen war ich so neugierig und wollte wissen warum der code mistlingt
danke dir black jack
Benutzeravatar
ThomasL
User
Beiträge: 1366
Registriert: Montag 14. Mai 2018, 14:44
Wohnort: Kreis Unna NRW

Wenn du das korrekt abgetippt hast, fehlt da definitiv an mehreren Stellen ein self.
In Javascript gibt es ein ähnliches this.
Daniel Shiffman von the Coding Train vergisst es während Live Coding Streams so oft,
das ihm extra ein This dot Song gewidmet wurde.
https://www.youtube.com/watch?v=M5d7vygUPoQ
Schade das es das nicht für self. gibt :D :shock: :D :lol: :lol: :lol:
Ich bin Pazifist und greife niemanden an, auch nicht mit Worten.
Für alle meine Code Beispiele gilt: "There is always a better way."
https://projecteuler.net/profile/Brotherluii.png
Antworten