Example 1: how to make a class in python
class Person:
def __init__(self, _name, _age):
self.name = _name
self.age = _age
def sayHi(self):
print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
Example 2: how to declare a class in python
class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
def __init__(self, var1=0, var2):
#the name of the construct must be "__init__" or it won't work
#the arguments "self" is mandatory but you can add more if you want
self.age = var1
self.name = var2
#the construct will be execute when you declare an instance of this class
def otherFunction(self):
#the other one work like any basic fonction but in every methods,
#the first argument (here "self") return to the class in which you are
Example 3: class methods in python
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
Example 4: 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 5: class and object in python
#NOTES
class PartyAnimal:
def Party():
#blahblah
an=PartyAnimal()
an.Party()# this is same as 'PartyAnimal.Party(an)'
Example 6: class in python
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)
# Call get_data() method
# Output: 2+3j
num1.get_data()
# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
num2.attr = 10
# Output: (5, 0, 10)
print((num2.real, num2.imag, num2.attr))
# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
print(num1.attr)