classPerson:def__init__(self, _name, _age):
self.name = _name
self.age = _age
defsayHi(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!
classPerson:# class static variable
person_type ="Human"# class constructordef__init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
# initialized class methoddefget_full_name(self):returnf"{self.first_name}{self.last_name}"# initialized class methoddefintroduce(self):returnf"Hi. I'm {self.first_name}{self.last_name}. I'm {self.age} years old."# class static method@staticmethoddefclass_name(self):return'Person'# class method@classmethoddefcreate_anonymous(cls):return Person('John','Doe',25)# dunder method - return class as a string when typecast to a stringdef__str__(self):returnf"str firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"# dunder method - return class a string then typecast to representativedef__repr__(self):returnf"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 classesdef__add__(self, other):return self.age + other.age
# create a person class
bob = Person(first_name="John", last_name="Doe", age=41)# print static methodprint(Person.class_name(Person))# print new class personprint(Person.create_anonymous().get_full_name())# print class static methodprint(Person.person_type)# print string representation of classprint(bob)# print representation of classprint(repr(bob))# add Person classes ages using dunder methodprint(bob + bob)
classPerson:#set name of class to call it def__init__(self, name, age):#func set ver
self.name = name#set name
self.age = age#set agedefmyfunc(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
classBox(object):#(object) ending not requireddef__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
defwriteAboutBox(self):# self is almost always required for a function in a class, unless you don't want to use any of the global class variablesprint(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
# Standard way of writing a simple classclassPerson1:# Type hinting not requireddef__init__(self, name:str, age:int, num_children=0):
self.name = name
self.age = age
self.num_children = num_children
def__repr__(self):returnf'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()classPerson2:""" 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 typedef__repr__(self):returnf'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
classAnimal(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 itdefoverview(self):# A function that uses the params of the __init__ functionprint(f"This species is called a {self.species} and the price for it is {self.price}")classFish(Animal):# Inherits from Animalpass# 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
classClassName(object):#"(object)" isn't mandatory unless this class inherit from anotherdef__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 classdefotherFunction(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
# plz suscribe to my youtube channel --># https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-AclassFan:def__init__(self, company, color, number_of_wings):
self.company = company
self.color = color
self.number_of_wings = number_of_wings
defPrintDetails(self):print('This is the brand of',self.company,'its color is', self.color,' and it has',self.number_of_wings,'petals')defswitch_on(self):print("fan started")defswitch_off(self):print("fan stopped")defspeed_up(self):print("speed increased by 1 unit")defspeed_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 classis a block of code that holds various functions. Because they
are located inside a classthey are named methods but mean the samne
thing. In addition variables that are stored inside a classare named
attributes. The point of a classis to call the classlater allowing you
to access as many functions or(methods)as you would like with the same
classname. These methods are grouped together under one classname due
to them working in association with eachother in some way.
classPerson:def__init__(self, name, age):
self.name = name
self.age = age
defsay_name(self):print(f"Hello, I am {self.name}")
p1 = Person("Sara",18)
p1.say_name()
classParrot:# class attribute
species ="bird"# instance attributedef__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 attributesprint("Blu is a {}".format(blu.__class__.species))print("Woo is also a {}".format(woo.__class__.species))# access the instance attributesprint("{} is {} years old".format( blu.name, blu.age))print("{} is {} years old".format( woo.name, woo.age))
classParrot:# class attribute
species ="bird"# instance attributedef__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 attributesprint("Blu is a {}".format(blu.__class__.species))print("Woo is also a {}".format(woo.__class__.species))# access the instance attributesprint("{} is {} years old".format( blu.name, blu.age))print("{} is {} years old".format( woo.name, woo.age))
# Node classclassNode:# Function to initialize the node objectdef__init__(self, data):
self.data = data # Assign data
self.next=None# Initialize# next as null# Linked List classclassLinkedList:# Function to initialize the Linked# List objectdef__init__(self):
self.head =None
classFoo:def__init__(self):
self.definition = Foo!
defhi():# Some other code here :)# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
classIntellipaatClass:
a =5deffunction1(self):print(‘Welcome to Intellipaat’)#accessing attributes using the class object of same name
IntellipaatClass.function(1)print(IntellipaatClass.a)
classDog:defbark(self):print("Woof!")defroll(self):print("*rolling*")defgreet(self):print("Greetings, master")defspeak(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
classawwab(object):def__init__(self, name, age):
self.name = name
self.age = age
defspeak(self):print("Hello, my name is",self.name,"and I am",self.age,"years old!")
awwabasad = awwab("Awwab Asad",11)print(awwabasad.speak())
classPerson:def__init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
defgreet(self, person_to_greet):# person_to_greet will be another Person objectprint(f"Hey {person_to_greet.name}, nice to meet you I'm {self.name}")defask_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
classPerson:def__init__(self, name, age):
self.name = name
self.age = age
# a class method to create a# Person object by birth year.
@classmethoddeffromBirthYear(cls, name, year):return cls(name, date.today().year - year)# a static method to check if a# Person is adult or not.
@staticmethoddefisAdult(age):return age >18
person1 = Person('mayank',21)
person2 = Person.fromBirthYear('mayank',1996)print(person1.age)print(person2.age)# print the resultprint(Person.isAdult(22))
>>>print(ObjectCreator)# you can print a class because it's an object<class'__main__.ObjectCreator'>>>>defecho(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>
"""
: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.
"""classEmployees:
no_of_leaves =8def__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
@classmethoddefalternative__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 functionsreturn cls(*_input_string.split("-"))@classmethoddefchange_leave_class_method(cls, _new__leave):
cls.no_of_leaves = _new__leave
defreturn__employee_statement(self):returnf"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)