Наследование классов в питоне - PullRequest
0 голосов
/ 05 мая 2019

Здравствуйте, мои вопросы о практике

Создайте класс YPSurvey в своем собственном файле, который расширяет класс Survey.Вот заголовок для конструктора: def__init __ (self, database) Конструктор YPSurvey вызовет конструктор класса Survey для создания соединения.Класс YPSurvey будет иметь свой собственный частный курсор, созданный из объекта Connection базы данных

Вот так выглядит мой класс опроса

    """
File survey.py
Accesses the demographics data in a sqlite3 survey database
"""

import sqlite3


class Survey:
    """Represents survey information contained in a Demographic table"""

def __init__(self, database):
    """Constructor creates a Survey object and connects to a
    Survey database using the input database parameter. 
    A cursor is also initialized to execute queries and hold the data.
    Initializes a List for use in retrieving demographic information."""
    self.__databaseName = database
    self.__conn = sqlite3.connect(database)
    self.__cur = self.__conn.cursor()
    self.__demographicList = list()

def __str__(self):
    """Returns the database name"""
    return print("Connected to "+str(self.__databaseName))

def getConn(self):
    """Returns the database connection for use by child class objects"""
    return self.__conn       

def clearDemographicList(self):
    """Clears the demographicList for reuse"""
    self.__demographicList.clear()

def getNumberOfPersonIDs(self):
    """Returns the total number of people who took the survey"""
    self.__cur.execute('Select count(PersonID) from Demographics')
    for row in self.__cur:
        total = row
    return total

def getNumberByDemographic(self, userDemographic):
    """Returns a copy of the demographicList, filled with the number of
    people in a particular demographic.
    Example: if userDemographic = "Gender", demographicList will contain
    a list of tuples with the number of females and males who took the survey"""
    self.clearDemographicList()
    self.__cur.execute("Select "+userDemographic+", count(?) from Demographics group by "
                       +userDemographic,(userDemographic,) )
    for row in self.__cur:
        self.__demographicList.append(row)
    return self.__demographicList

, и так выглядит мой класс YPSurveyкак

import sqlite3
class YPSurvey_Final:

def __init__(self, database):
    self.__databaseName = database
    self.__conn = sqlite3.connect(database)
    self.__cur = self.__conn.cursor()
    self.__phobiaList = list()
    self.__demographicList = list()
    self.__phobia_nameList = list()


def getNumberOfEachPhobia(self):
    """Returns the total number of people who took the survey"""
    self.__cur.execute("SELECT Phobia, COUNT(*) FROM Phobias GROUP BY Phobia ORDER BY Phobia DESC")
    for row in self.__cur:
        self.__phobiaList.append(row)
    return self.__phobiaList
def phobias(self):
    print('I counted this many phobias: {}'.format(len(self.__phobiaList)))
    for phobia in self.__phobiaList:
        print('Phobia and # of people: {}'.format(phobia))

def phobias_names(self):
    print('There is this many:{}'.format(len(self.__phobia_nameList)))
    for phobias_n in self.__phobia_nameList:
        print ("test",phobias_n)
def clearDemographicList(self):
    """Clears the demographicList for reuse"""
    self.__demographicList.clear()              
def getNumberByDemographic(self, userDemographic, phobia_name):
    self.clearDemographicList()
    self.__cur.execute("SELECT "+userDemographic+", phobia, 1.0 * COUNT(*) / (SELECT COUNT(*) FROM Phobias) AS percentage FROM Demographics,Phobias WHERE Phobia = ? GROUP BY "+userDemographic+"",(phobia_name,))
    for row in self.__cur:
        self.__demographicList.append(row)
    return self.__demographicList

def demographics(self):
    for demographic in self.__demographicList:
        print(demographic)
def phobia_names(self):
    for phobia_name in self.__phobia_nameList:
        print(phobia_name)

Так что я не понимаю, что означает «расширяет класс Survey» и как я могу изменить свой класс опроса YP для работы с классом Survey?

Ответы [ 2 ]

0 голосов
/ 05 мая 2019

"extends" часто используется в ООП для сигнализации наследования.Вы можете сделать свой класс наследуемым от другого. Вот так:

class MyClass(BaseClass):

И вы можете делать такие вещи, как делегировать вызов конструктору супер- / базового класса с помощью метода super Вот так:

def __init__(self):
    super().__init__()
0 голосов
/ 05 мая 2019

Если вы ищете расширение YPSurvey_Final из класса Survey, вам необходимо заменить определение класса для YPSurvey_Final следующим образом:

class YPSurvey_Final(Survey):
    ....
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...