new object python 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() # Prints: Hello, my name is Bob and I am 25 years old!
Example 2: python class
class Animal(object): # Doesn't need params but put it there anyways.
def __init__(self, species, price):
self.species = species # Sets species name
self.price = price # Sets price of it
def overview(self): # A function that uses the params of the __init__ function
print(f"This species is called a {self.species} and the price for it is {self.price}")
class Fish(Animal): # Inherits from Animal
pass # Don't need to add anything because it's inherited everything from Animal
salmon = Fish("Salmon", "$20") # Make a object from class Fish
salmon.overview() # Run a function with it
dog = Animal("Golden retriever", "$400") # Make a object from class Animal
dog.overview() # Run a function with it
Example 3: how to declare a class in python
class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
def __init__(self, var1=0, var2):
#the name of the construct must be "__init__" or it won't work
#the arguments "self" is mandatory but you can add more if you want
self.age = var1
self.name = var2
#the construct will be execute when you declare an instance of this class
def otherFunction(self):
#the other one work like any basic fonction but in every methods,
#the first argument (here "self") return to the class in which you are
Example 4: what is an object in python
#objects are collections of data
Example 5: how to create an object in python
class ClassName:
self.attribute_1 = variable_1 #Set attributes for all object instances
self.attrubute_2 = variable_2
def __init__(self, attribute_3, attribute_4): #Set attributes at object creation
self.attribute_3 = attribute_3
self.attribute_4 = attribute_4
def method(self): #All methods should include self
print("This is a method example.") #Define methods just like functions
object = Object(4, "string") #Set attribute_3 and attribute_4
object.method() #Methods are called like this.
Example 6: How to make a new class in python
#Use the class function and give the class a name
#next use the def __init__() to initilaize and give it some properties.
class Fruits():
def __init__(self, name, colour, taste):
self.name = name
self.colour = colour
self.taste = taste
#Now create an object by first calling the class
fruit1 = Fruits(apple, red, sweet)
print(fruit1.name)
#this will print the name which is apple
print(fruit1.colour)
#this will print the colour which is red
print(fruit1.taste)
#this will print the taste which is sweet