python create instance of class code example
Example 1: call instance class python
class example:
def __call__(self):
print("It worked!")
g = example()
g()
Example 2: 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 3: making an instance of a class in puython
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Example 4: python instance Object
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
Example 5: How to make a new class in python
class Fruits():
def __init__(self, name, colour, taste):
self.name = name
self.colour = colour
self.taste = taste
fruit1 = Fruits(apple, red, sweet)
print(fruit1.name)
print(fruit1.colour)
print(fruit1.taste)