python instance code example
Example 1: declare class python
# To create a simple class:
class Shape:
def __init__():
print("A new shape has been created!")
pass
def get_area(self):
pass
# To create a class that uses inheritance and polymorphism
# from another class:
class Rectangle(Shape):
def __init__(self, height, width): # The constructor
super.__init__()
self.height = height
self.width = width
def get_area(self):
return self.height * self.width
Example 2: class python
class MyClass(object):
def __init__(self, x):
self.x = x
Example 3: instance method in python
# Instance Method Example in Python
class Student:
def __init__(self, a, b):
self.a = a
self.b = b
def avg(self):
return (self.a + self.b) / 2
s1 = Student(10, 20)
print( s1.avg() )
Example 4: class variable in python
# Class variables refer to variables that are made within a class.
# It is generated when you define the class.
# It's shared with all the instance of that class.
# Example:
class some_variable_holder(object):
var = "This variable is created inside the class some_variable_holder()."
def somefunc(self):
print("Random function ran.")
thing = some_variable_holder()
another_thing = some_variable_holder()
# Both does the same thing because the same variable has been passed on from the class.
thing.var
another_thing.var