python def class code example
Example 1: python define class
class uneclasse():
def __init__(self):
pass
def something(self):
pass
xx = uneclasse()
xx.something()
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: python class
class Animal(object):
def __init__(self, species, price):
self.species = species
self.price = price
def overview(self):
print(f"This species is called a {self.species} and the price for it is {self.price}")
class Fish(Animal):
pass
salmon = Fish("Salmon", "$20")
salmon.overview()
dog = Animal("Golden retriever", "$400")
dog.overview()
Example 5: classes in python
class Person():
alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f'Hello, my name is {self.name} and my age is {self.age}')
person_one = Person('Sam', 23)
person_one.speak()
==================================================================
>>> 'Hello, my name is Sam and my age is 23'