class in function python code example
Example 1: 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 2: How to make a new class in python
#Use the class function and give the class a name
#next use the def __init__() to initilaize and give it some properties.
class Fruits():
def __init__(self, name, colour, taste):
self.name = name
self.colour = colour
self.taste = taste
#Now create an object by first calling the class
fruit1 = Fruits(apple, red, sweet)
print(fruit1.name)
#this will print the name which is apple
print(fruit1.colour)
#this will print the colour which is red
print(fruit1.taste)
#this will print the taste which is sweet