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!
class Person:
# class static variable
person_type = "Human"
# class constructor
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
# initialized class method
def get_full_name(self):
return f"{self.first_name} {self.last_name}"
# initialized class method
def introduce(self):
return f"Hi. I'm {self.first_name} {self.last_name}. I'm {self.age} years old."
# class static method
@staticmethod
def class_name(self):
return 'Person'
# class method
@classmethod
def create_anonymous(cls):
return Person('John', 'Doe', 25)
# dunder method - return class as a string when typecast to a string
def __str__(self):
return f"str firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"
# dunder method - return class a string then typecast to representative
def __repr__(self):
return f"repr firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"
# dunder method - return sum of ages when using the + operator on two Person classes
def __add__(self, other):
return self.age + other.age
# create a person class
bob = Person(first_name="John", last_name="Doe", age=41)
# print static method
print(Person.class_name(Person))
# print new class person
print(Person.create_anonymous().get_full_name())
# print class static method
print(Person.person_type)
# print string representation of class
print(bob)
# print representation of class
print(repr(bob))
# add Person classes ages using dunder method
print(bob + bob)
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
class Person:#set name of class to call it
def __init__(self, name, age):#func set ver
self.name = name#set name
self.age = age#set age
def myfunc(self):#func inside of class
print("Hello my name is " + self.name)# code that the func dose
p1 = Person("barry", 50)# setting a ver fo rthe class
p1.myfunc() #call the func and whitch ver you want it to be with
# Standard way of writing a simple class
class Person1:
# Type hinting not required
def __init__(self, name: str, age: int, num_children=0):
self.name = name
self.age = age
self.num_children = num_children
def __repr__(self):
return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'
from dataclasses import dataclass
# A class using data classes. Dataclasses are simpler but can't support operations during initialization
@dataclass()
class Person2:
""" This class handles the values related to a person. """
name: str # Indicating types is required
age: int
num_children = 0 # Default values don't require an indication of a type
def __repr__(self):
return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'
# Both classes (Person1 and Person2) achieve the same thing but require different code to do it
person1 = Person1('Joe', 28, 2)
print(person1)
# Result: My name is Joe, I am 28 years old, and I have 2 children
person2 = Person2('Emma', 19)
print(person2)
# Result: My name is Emma, I am 19 years old, and I have 0 children
class Animal(object): # Doesn't need params but put it there anyways.
def __init__(self, species, price):
self.species = species # Sets species name
self.price = price # Sets price of it
def overview(self): # A function that uses the params of the __init__ function
print(f"This species is called a {self.species} and the price for it is {self.price}")
class Fish(Animal): # Inherits from Animal
pass # Don't need to add anything because it's inherited everything from Animal
salmon = Fish("Salmon", "$20") # Make a object from class Fish
salmon.overview() # Run a function with it
dog = Animal("Golden retriever", "$400") # Make a object from class Animal
dog.overview() # Run a function with it
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
class Employee(Object)
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __str__(self)
return f"Employee {name}
hes age {age}
and make {salary}"
# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A
class Fan:
def __init__(self, company, color, number_of_wings):
self.company = company
self.color = color
self.number_of_wings = number_of_wings
def PrintDetails(self):
print('This is the brand of',self.company,'its color is', self.color,' and it has',self.number_of_wings,'petals')
def switch_on(self):
print("fan started")
def switch_off(self):
print("fan stopped")
def speed_up(self):
print("speed increased by 1 unit")
def speed_down(self):
print("speed decreased by 1 unit")
usha_fan = Fan('usha','skin',5)
fan = Fan('bajaj','wite', 4)
print('these are the details of this fan')
usha_fan.PrintDetails()
print()
usha_fan.switch_on()
A class is a block of code that holds various functions. Because they
are located inside a class they are named methods but mean the samne
thing. In addition variables that are stored inside a class are named
attributes. The point of a class is to call the class later allowing you
to access as many functions or (methods) as you would like with the same
class name. These methods are grouped together under one class name due
to them working in association with eachother in some way.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_name(self):
print(f"Hello, I am {self.name}")
p1 = Person("Sara", 18)
p1.say_name()
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize
# next as null
# Linked List class
class LinkedList:
# Function to initialize the Linked
# List object
def __init__(self):
self.head = None
class Foo:
def __init__(self):
self.definition = Foo!
def hi():
# Some other code here :)
# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
class IntellipaatClass:
a = 5
def function1(self):
print(‘Welcome to Intellipaat’)
#accessing attributes using the class object of same name
IntellipaatClass.function(1)
print(IntellipaatClass.a)
class Dog:
def bark(self):
print("Woof!")
def roll(self):
print("*rolling*")
def greet(self):
print("Greetings, master")
def speak(self):
print("I cannot!")
# Creating the Dog class instance and saving it to the variable <clyde>
clyde = Dog()
clyde.bark() # --> Woof!
clyde.roll() # --> *rolling*
clyde.greet() # --> Greetings, master
clyde.speak() # --> I cannot!
# Creating another Dog instance
jenkins = Dog()
jenkins.bark() # --> Woof!
jenkins.roll() # --> *rolling*
# .. And other methods
# .. Infinite objects can be created this way, all implementing the same methods defined in our class
class awwab(object):
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("Hello, my name is",self.name,"and I am",self.age,"years old!")
awwabasad = awwab("Awwab Asad", 11)
print(awwabasad.speak())
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def greet(self, person_to_greet):
# person_to_greet will be another Person object
print(f"Hey {person_to_greet.name}, nice to meet you I'm {self.name}")
def ask_age(self, ask_from):
print(f"{self.name}: {ask_from.name}, How old are you?")
print(f"{ask_from.name}: i am {ask_from.age}")
# Creating a person object
tom = Person("Tom", 50, "Male")
# we can also create an object with keyword arguments
jack = Person(name="Jack", age=19, gender="Male")
# Here we call the greet method of tom, and we pass the Jack Person Object Created above
tom.greet(jack)
# if we call the greet method of jack and pass the Tom person object, then jack greets tom
jack.greet(tom)
# Here Jack will ask age of tom, and tom will reply with his age
jack.ask_age(tom)
# Python program to demonstrate
# use of a class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a
# Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a
# Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print(person1.age)
print(person2.age)
# print the result
print(Person.isAdult(22))
# ---------------------------------------- Object Oriented Programming ------------------------------------- #
# It Is Based On Three Pillars = Encapsulation = ( self ) / - Inheritance / - Polymorphism /
# Constructor ==> __init__(self) / self => Default Parameter // Self Can Be Named AnyThing You Need
# Class ==> / Like The Real Class And You Putted Inside Her Somethings Like = ( Constructor, Methods, Attributes )
# print( classname.__class__ ) ==> / If You Need To Know THe Class Follow What ?
# If You Wanna Run The Class You Need To Call Her In Variable = ( x = ClassName
x.Thing )
# Inheritance ==> / If You Have Class In Your Project And You Wanna Put In Something
# You Create The New Class And Give Her The Class Name You Need As A Parameter
# Polymorphism Take The Same Elements From The Inheritance But Do Something Deference Or Any Some Like
# ==> + Between The Numbers Do Addition But Between Strings Do Concatenation
# super() ==> If You Need Inheriting A Constructor From Another Class :-
# You Need Use super() Method / :-
# You Type InSide Your Class Under You //> __Init__( self, What You Need Inheriting From Old Class ) :
# super( Your Class, self ).__init__( What You Need Inheriting From Old Class, And Your New Additions ) :
# If you Need Addition Something Like :
# print( "Hello, Im From 'Super'" )
# Inheriting From Class Or More :-
# If We Have 4 Class A,B,C,D
# A Inside Her Function Do ==> ( "Doing From 'A'" )
# B Inheriting From A
# C Inside Her Function Do ==> ( "Doing From 'C'" )
# D Inheriting From B,A
# If We Run The Function Inside D Will Print ==> Doing From 'A'
# Because He Start From 'B' Because 'B' The First Class 'D' Inheriting From, After This Go
# To 'A' // Because 'B' Inheriting From 'A' Will Print => Doing From 'A' /
# If If He Does Not Find Anything In 'A'
# He Back And Go To 'C'
# If You Need Know The Way Just Type ==> print( TheClassName.mro() )
>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
... print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>
fromr random import radint
Asnwer= randint(1,200)
count= 0
while true:
guess = getingeger("whatis yourestimate")
if guess< 1 or guess > 200:
print(your estimate must be between 1 and 200)
continue
count+ = 1
if guess < answer:
print("higher")
elif guess > answer:
print("lower")
else:
print("you guessed it!")
if count== 1
print("wow first try!!")
else:
print("you estimated it in, count,'time'")
"""
:return : Simple class methods with an alternative constructor, just only take
an input of the data in the form of string and return it into the
instance variable.
"""
class Employees:
no_of_leaves = 8
def __init__(self, _age, _name, _leave, _salary, _work_experience):
self.name = _name
self.age = _age
self.leave = _leave
self.salary = _salary
self.work_experience = _work_experience
@classmethod
def alternative__constructor_class(cls, _input_string):
"""
:param _input_string: Takes the input from the function from the class,
:return: The alternative__constructor works to add data only one string and then,
return it into the object.
:parameter: Class methods as the alternative constructor.
"""
# params_split = _input_string.split("-")
# print(params_split)
# return cls(params_split[0], params_split[1], params_split[2], params_split[3], params_split[4])
# Multi liner functions
return cls(*_input_string.split("-"))
@classmethod
def change_leave_class_method(cls, _new__leave):
cls.no_of_leaves = _new__leave
def return__employee_statement(self):
return f"Name : {self.name} Age : {self.age} leave : {self.leave} salary : {self.salary}"
f"Work Experience : {self.work_experience}"
anshu = Employees(_name="Anshu", _salary=70000, _leave=8, _work_experience=6, _age=16)
shivam = Employees.alternative__constructor_class("shivam-16-7000-4-2")
print(shivam.return__employee_statement())
anshu.change_leave_class_method(30)
print(Employees.no_of_leaves)