how to create objects of a class in 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: python person class
import datetime
class Person:
def __init__(self, name, surname, birthdate, address, telephone, email):
self.name = name
self.surname = surname
self.birthdate = birthdate
self.address = address
self.telephone = telephone
self.email = email
def age(self):
today = datetime.date.today()
age = today.year - self.birthdate.year
if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day):
age -= 1
return age
person = Person(
"Jane",
"Doe",
datetime.date(1992, 3, 12),
"No. 12 Short Street, Greenville",
"555 456 0987",
"[email protected]"
)
print(person.name)
print(person.email)
print(person.age())