xxxxxxxxxx
# A Python program to demonstrate working of class
# methods
class Vector2D:
x = 0.0
y = 0.0
# Creating a method named Set
def Set(self, x, y):
self.x = x
self.y = y
def Main():
# vec is an object of class Vector2D
vec = Vector2D()
# Passing values to the function Set
# by using dot(.) operator.
vec.Set(5, 6)
print("X: " + str(vec.x) + ", Y: " + str(vec.y))
if __name__=='__main__':
Main()
xxxxxxxxxx
JavaScript Class Method
How to define and use a Class method.
<body>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
</body>
xxxxxxxxxx
"""Class Method
"""class method are bound to class rather than an instance"""
"""class method takes cls as first argument"""
"""Thoughclassmethod arenot boundto any instance,they canbe invoked by instance of class"""
""" This is because it enable themto access and modify class attributes if needed"""
class Circle:
pi = 3.14
def __init__(self, radius):
self.radius = radius
"""Instance method for area calculation (recommended for direct calculations)"""
def calculate_area(self):
return self.pi * self.radius**2
"""Class method for area calculation (alternative approach)"""
@classmethod
def calculate_area_from_radius(cls, radius):
return cls.pi * radius**2
""" Using the instance method:"""
circle1 = Circle(7)
area = circle1.calculate_area()
print(area) * Output: 153.86
"""Using the class method (less common for direct calculations):"""
area = Circle.calculate_area_from_radius(7)
print(area) * Output: 153.86