Skip to main content
 首页 » 编程设计

python之为什么要使用类

2025年05月04日15lvdongjie

<分区>

我转换了这个“非面向对象”的代码:

from Tkinter import * 
 
root = Tk() 
frame = Frame(root) 
frame.pack() 
 
bottomframe = Frame(root) 
bottomframe.pack( side = BOTTOM ) 
 
redbutton = Button(frame, text="Red", fg="red") 
redbutton.pack( side = LEFT) 
 
bluebutton = Button(frame, text="Blue", fg="blue") 
bluebutton.pack( side = LEFT ) 
 
root.mainloop() 

这个面向对象的代码:

from Tkinter import * 
class Window(Frame): 
    def __init__(self, parent = None): 
       Frame.__init__(self, parent) 
       self.pack() 
 
       widget=Button(self,text="Red", fg = "red") 
       widget.pack(side = LEFT) 
 
       widget = Button(self, text ="Blue", fg = "blue") 
       widget.pack(side = RIGHT) 
if __name__== '__main__': 
    Window().mainloop() 

这两个片段都会在屏幕上弹出一个简单的窗口。我的问题是,在这种情况下,面向对象编程(即类的使用)有什么好处?

如果我想生成 3 个其他窗口(使用类),但按钮颜色已更改,我是否必须修改蓝图(即类),或者在调用类实例时是否有任何方法可以做到这一点?