# Python的GUI开发 **Repository Path**: researchimage/pythonGUI ## Basic Information - **Project Name**: Python的GUI开发 - **Description**: No description available - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-04-06 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #Python的GUI开发 ## 构造方法 构造方法和其他普通方法不同的地方在于,当一个对象被创建后,会立即调用构造方法。 ```python >>>f=Foobar() >>>f.init() ``` 构造方法能让它简化成如下形式。 ```python >>>f=FooBar() ``` 在python中创建一个构造方法,只要把init方法的名字从简单的init修改为魔法版本__init__ 即可: ```python class FooBar: def __init__(self): self.somevar=42 >>>f=FooBar() >>>f.somevar 42 ``` 重写是继承机制中的一个重要内容,对于构造方法尤其重要。如果一个类的构造方法被重写,那么就需要调用超类的构造方法,否则对象可能不会被正确地初始化。 ```python class Bird: def __init__(self): self.hungry=True def eat(self): if self.hungry: print("Aaaah...") else: print("No,thanks!") class SongBird(Bird): def __init__(self): self.sound='Squawk!' def sing(self): print(self.sound) ``` 因为SongBird是Bird的一个子类,它继承了eat方法,但如果调用eat方法,就会产生一个问题: ``` sb.eat() Traceback (most recent call last) AttributeError:SongBird instance has no attribute 'hungry' ``` 在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。 ```python class SongBird(Bird): def __init__(self): Bird.__init__(self) self.sound='Squawk!' def sing(self): print(self.sound) ``` 在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上。但如果直接调用类的方法(比如Bird.__init__),那么就没有实例会被绑定。这样就可以自由提供需要的self参数。 # 旧版和新版超类构造方法 旧版: ```python class SongBird(Bird): def __init__(self): Bird.__init__(self) self.sound='Squawk!' def sing(self): print(self.sound) ``` 新版: ```python __metaclass__=type class Bird: def __init__(self): self.hungry=True def eat(self): if self.hungry: print('Aaaah...') self.hungry=False else: print('No,thanks!') class SongBird(Bird): def __init__(self): super(SongBird,self).__init__() self.sound='Squawk!' def sing(self): print(self.sound) ``` python3.0中,super函数可以不带任何参数进行调用。 为了确保类是新型的,应该把赋值语句__metaclass__=type放在模块的最开始,或者(直接或间接)子类化内建类object。 ```python class NewStyle(object): more_code_here class OldStyle: more_code_here ``` NewStyle是新式类,OldStyle是旧式类,如果文件以metaclass=type开始,那么两个都是新式类。