Classes And Objects
- Similar to having a whole kitchen, toaster, microwave, dish washer, all with different nodes.
- What if we want two separate kitchens with separate appliances.
- The class deals with this.
- Class names use uppercase letters.
- In the indented line, we define all the functions and attributes that a dog has.
__init__is for initialisation. The function is called, whenever an instance of the classDogis created.- Two underscores on either side are specially defined by Python.
- Makes sure the computer recognises
__init__as the initialisation function.
- Makes sure the computer recognises
selfis the specific instance of theDogclass after it has been initialised.selfis passed to thespeakfunction.- Then provides you access to any of the attributes or functions under the
def __init__(self)class.
- Then provides you access to any of the attributes or functions under the
self.nameconcatenates the Dogs name with the' says: Bark!'string.my_dog = Dog(), themy_dogis equal to a newly created instance of the classDog.- When the above is ran, the
__init__function get called and an instance of theDogclass is returned.
- When the above is ran, the
- Remember, variables and functions are lowercase and classes start with an uppercase character.
-
Running
my_dog.speak()will outputRover says: Bark!``` class Dog: def init(self): self.name = ‘Rover’ self.legs = 4def speak(self): print(self.name + ' says: Bark!')
my_dog = Dog() another_dog = Dog()
my_dog.speak()
* How to give dogs difference names and provide a name when we initialise the dog.
class Dog: def init(self, name): self.name = name self.legs = 4
def speak(self):
print(self.name + ' says: Bark!')
my_dog = Dog(‘Rover’) another_dog = Dog(‘Fluffy’)
my_dog.speak()
* Running `my_dog = Dog('Rover')` will output `Rover says: Bark!`
* Running `another_dog = Dog('Fluffy')` will output `Fluffy says: Bark!`
* If use .function syntax such as `.speak()` the class instance of `my_dog` is passed in as a variable.
* Class Instances are also called Objects, hence "Object Oriented Programming".
* Variables inside the classes such as `self.name = name` are called Attributes.
* The functions inside such the below are called Methods (or Class Methods).
def speak(self):
print(self.name + ' says: Bark!') ``` * The `Dog` object has the Method `Speak`.