In [1]:
# Basic class
class Sample():
pass
In [2]:
my_sample = Sample()
In [4]:
type(my_sample)
Out[4]:
In [5]:
# Parameters
class Dog():
def __init__(self, breed):
self.breed = breed
In [7]:
my_lab = Dog("lab")
In [8]:
my_lab.breed
Out[8]:
In [18]:
# Shows a class with init and a class method
class Dog():
def __init__(self, breed, name):
self.breed = breed
self.name = name
def bark(self):
print("{} is barking".format(self.name))
In [17]:
my_lab = Dog("Lab", "Jimmy")
my_lab.bark()
In [19]:
# Class object attribute
class Circle():
pi = 3.14 # This is common across all class objects
def __init__(self, radius=1):
self.radius = radius
def calculateCircumference(self):
return self.radius * self.pi * 2
In [26]:
my_c = Circle(10)
my_c.calculateCircumference()
Out[26]:
In [32]:
# Class object attribute
class Circle():
pi = 3.14 # This is common across all class objects
def __init__(self, radius=1):
self.radius = radius
#self.area = radius * radius * self.pi
self.area = radius * radius * Circle.pi # Class level attributes can also be called this way!
def calculateCircumference(self):
return self.radius * self.pi * 2
In [33]:
c = Circle()
In [34]:
c.area
Out[34]:
In [35]:
c.radius
Out[35]:
In [36]:
c.calculateCircumference()
Out[36]:
In [44]:
class Animal():
def __init__(self):
print("Animal created")
def eat(self):
print("Animal am eating")
def sleep(self):
print("Animal am sleeping")
In [45]:
a = Animal()
In [46]:
a.eat()
a.sleep()
In [51]:
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog created")
def bark(self):
print("Dog is barking")
In [52]:
d = Dog()
In [53]:
d.eat()
In [54]:
d.sleep()
In [55]:
d.bark()
In [ ]: