les classes en python code example
Example 1: python classes
class Box(object): #(object) ending not required
def __init__(self, color, width, height): # Constructor: These parameters will be used upon class calling(Except self)
self.color = color # self refers to global variables that can only be used throughout the class
self.width = width
self.height = height
self.area = width * height
def writeAboutBox(self): # self is almost always required for a function in a class, unless you don't want to use any of the global class variables
print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
greenSquare = Box("green", 10, 10) #Creates new square
greenSquare.writeAboutBox() # Calls writeAboutBox function of greenSquare object
Example 2: classes in python
# Python classes
class Person():
# Class object attributes (attributes that not needed to be mentioned when creating new class of person)
alive = True
def __init__(self, name, age):
# In the __init__ method you can make attributes that will be mentioned when creating new class of person
self.name = name
self.age = age
def speak(self):
# In every method in class there will be self, and then other things (name, age, etc.)
print(f'Hello, my name is {self.name} and my age is {self.age}') # f'' is type of strings that let you use variable within the string
person_one = Person('Sam', 23) # Sam is the name attribute, and 23 is the age attribute
person_one.speak() # Prints Hello, my name is Sam and my age is 23
==================================================================
# Output:
>>> 'Hello, my name is Sam and my age is 23'
Example 3: classes in python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John",
36)
print(p1.name)
print(p1.age)