xxxxxxxxxx
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating instances
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
xxxxxxxxxx
An object belonging to a class. e.g. if you had an Employee class, each
individual employee would be an instance of the Employee class
xxxxxxxxxx
class MyClass:
pass
my_object = MyClass()
if isinstance(my_object, MyClass):
print("my_object is an instance of MyClass")
else:
print("my_object is not an instance of MyClass")
xxxxxxxxxx
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(type(obj_triangle) == Triangle) # true
print(type(obj_triangle) == Polygon) # false
print(isinstance(obj_polygon, Polygon)) # true
print(isinstance(obj_triangle, Polygon)) # true
xxxxxxxxxx
# 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() )
xxxxxxxxxx
class Const:
def __init__(self, firstName, lastName):
self.firstName = firstName
def hello(self):
print("hello world this is my sentence")
c = Const("hello", "world")
print(c.firstName)
c.hello()