- Tkinter GUI Programming by Example
- David Love
- 314字
- 2021-08-27 18:49:10
Instances
An instance is one particular implementation of a class. Each separate instance of the same class can be completely independent from the others, or they can share attributes if the need arises.
Python uses a method called __init__ in order to initialize each instance of a class. This method can be used to set initial variables which differ between instances.
The easiest way to wrap your head around using classes is to see an example:
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print("Woof! My name is", self.name)
This code gives us a class called Dog. The _init_ function of Dog takes two arguments: self and name.
The methods of a class require the first argument to be self in order to give them access to the instance's attributes. This argument is passed automatically, so you will not need to worry about it. You will also see that the self argument is required for the speak method too.
All arguments following self are passed to the methods when calling them as normal.
Now, any instance of a Dog has access to its attributes (name) and its methods (speak). Let's create some instances of Dog:
dog_one = Dog('Rover')
dog_two = Dog('Rex')
dog_one.speak()
dog_two.speak()
Run this code and you should see two lines printed:
Woof! My name is Rover
Woof! My name is Rex
Both Dog instances have access to the same speak method, but each one calls it differently based on its attributes. This is the core concept of a class instance in a nutshell. The print function itself has been reused but has produced a slightly different outcome depending on the instance's attributes.
The main reason we use classes so much in GUI development is the ability to inherit the abilities of a widget but to better customize them to our particular application. Inheritance in Python is very simple to do.
- Spring Boot開發(fā)與測試實戰(zhàn)
- DevOps with Kubernetes
- Visual FoxPro程序設(shè)計教程
- OpenCV實例精解
- PostgreSQL技術(shù)內(nèi)幕:事務(wù)處理深度探索
- Blockly創(chuàng)意趣味編程
- Linux C編程:一站式學(xué)習(xí)
- Python語言實用教程
- PHP編程基礎(chǔ)與實踐教程
- Kivy Cookbook
- Flask Web開發(fā):基于Python的Web應(yīng)用開發(fā)實戰(zhàn)(第2版)
- Microsoft HoloLens By Example
- Java EE項目應(yīng)用開發(fā)
- Java服務(wù)端研發(fā)知識圖譜
- Mastering JavaScript Promises