何时创建新类?

2024-04-19 00:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我开始学习类,但什么时候应该创建一个新类而不是一个函数仍然有点困惑。我正在制作一个代码,从一个网站获取信息,将信息存储在数据库中,并用这些信息制作一个图表。(我目前有一个名为“Stats”的类正在这样做)我想使用Tkinter创建按钮,以便用户可以选择他想在图表中看到的信息类型,我的问题是,我是否应该为Tkinter创建一个不同的类来生成图形,还是应该将它们作为“Stats”类的函数来生成。这是我的密码:

from bs4 import BeautifulSoup
import urllib.request
import sqlite3
from matplotlib import pyplot as plt
from cairocffi import *
plt.style.use('ggplot')
plt.title('Online')
plt.ylabel('Number of players')

class Stats():
def __init__(self):
    self.conn = sqlite3.connect('test.db')
    self.c = self.conn.cursor()
    self.create_table()
    self.a = []
    url = "*************"
    page = urllib.request.urlopen(url)
    soup = BeautifulSoup(page.read(), 'html.parser')
    stats = soup.find_all("div", {"id":"RightArtwork"})
    number = soup.find_all("tr", {"class":"Odd"})

    for totalOnline in stats:
        divTotal = totalOnline.find_all("div")
        for totalOnline in divTotal:
            total = list(totalOnline.text)
            total[0:5] = [''.join(total[0:5])]
            total[1:19] = [''.join(total[1:19])]
            #self.number,self.name = total.split(",")
            self.number = int(total[0])
            self.name = str(total[1])
            #print(self.name)
            self.data_entry()
    self.graph()






def create_table(self):
    self.c.execute('CREATE TABLE IF NOT EXISTS testDB(name TEXT, number REAL)')

def data_entry(self):
    self.c.execute("INSERT INTO testDB(name, number) VALUES(?, ?)",
                   (self.name, self.number, ))
    self.conn.commit()

def comparison(self):
    highestNumber = self.c.execute('SELECT number FROM testDB ORDER BY number DESC LIMIT 1')
    for rows in highestNumber:
        print("The highest numbers of players online was " + str(rows[0]))

    lowestNumber = self.c.execute('SELECT number FROM testDB ORDER BY number ASC LIMIT 1')
    for rows in lowestNumber:
        print("The lowest number of players online was "+ str(rows[0]))

def graph(self):
    self.c.execute('SELECT number FROM testDB')
    values = []
    values2 = []
    i = 0
    for row in self.c.fetchall():
        floats = float(''.join(map(str,row)))
        values.append(floats)
        print(values[-1])
    while i < len(values):
        i = i + 1
        values2.append(i)

    self.comparison()

    plt.plot(values2,values)
    plt.show()
    self.c.close()
    self.conn.close()



Stats()

Tags: nameinimportselfnumberforexecutedef
1条回答
网友
1楼 · 发布于 2024-04-19 00:36:37

一般来说,把输出和计算分开是个好主意。 如果将Tkinter代码放在单独的类中:

class GUI(tk.frame):
    def __init__(self, stats):
        ...

那么您的Stats类可能更易于重用。你可以写其他脚本 使用Stats类,例如,使用Stats的命令行脚本 没有Tkinter,或者使用不同GUI框架的脚本,或者多个 以不同方式使用Stats的脚本。你知道吗

如果Stats代码与Tkinter代码纠缠在一起,那么这一切都不会发生 可能吧。你知道吗

要遵循上述建议,__init__方法不应调用graph。让 GUI代码可以做到这一点。你知道吗


任何可以用类解决的问题也可以用普通的 功能。有时使用类可以使代码更简洁,但是 避免将状态作为参数传递给每个 或者利用继承。你知道吗

当试图决定何时使用一个类时,试着想象一下代码会是什么 看起来像是类和普通函数。问问自己你得到了什么 通过使用类。是否存在子类化的可能性?有没有办法 继承的好处?代码是否通过使用 一个类而不是普通函数?类是否利用了special methods?考虑一下杰克·迪德里奇的建议 到Stop Writing Classes。你知道吗

如果不能确定使用类的好处,请使用函数。你知道吗

相关问题 更多 >