what is a python class code example
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: python define class
class uneclasse():
def __init__(self):
pass
def something(self):
pass
xx = uneclasse()
xx.something()
Example 3: class python
class MyClass(object):
def __init__(self, x):
self.x = x
Example 4: python class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name +".")
p1 = Person("Victor", 24)
p1.myfunc()
Example 5: 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 6: 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()