Example 1: how to make a class in python
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()
Example 2: class in python
class LuckyLemur():
def __init__(self, description):
self.description = description
def reveal_description(self):
print(f'Lucky Lemur is {self.description}')
lucky_lemur = LuckyLemur('Pro')
lucky_lemur.reveal_description()
Example 3: python classes
class Student:
def __init__(self, id, name, age):
self.name = name
self.id = id
self.age = age
def greet(self):
print(f"Hello there.\nMy name is {self.name}")
def get_age(self):
print(f"I am {self.age}")
def __add__(self, other)
return Student(
self.name+" "+other.name,
self.id + " "+ other.id,
str(self.age) +" "+str(other.age))
p1 = Student(1, "Jay", 19)
p2 = Student(2, "Jean", 22)
p3 = Student(3, "Shanna", 32)
p4 = Student(4, "Kayla", 23)
result = p1+p3
Example 4: class python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
---------------------------------------------------------------
40
Example 5: 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())