functions in classes python code example
Example 1: python classes
class Box(object):
def __init__(self, color, width, height):
self.color = color
self.width = width
self.height = height
self.area = width * height
def writeAboutBox(self):
print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
greenSquare = Box("green", 10, 10)
greenSquare.writeAboutBox()
Example 2: classes in python
class Foo:
def __init__(self):
self.definition = Foo!
def hi():
Example 3: class methods in python
from datetime import date
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: what is a class in python
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.