Categories
Programming Python TIL

Classes in Python

TIL About Classes in Python and Object Oriented Programming

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Python3 Documentation

Quick and dirty… Let’s dive into the code:

First the ‘class’ keyword followed by the name of the class ‘Human’. By convention, the class name in Python should be capitalized.

class Human:
  pass

To make a useful class we need to add an __init__() method. This method always requires self as an argument, and all other arguments defined here must be defined in the method.

class Human:
	def __init__(self, first, last, age)
    	self.first = first
        self.last = last
        self.age = age
        self.fullname = first + ' ' + last

Once we’ve created the class, we can create a new instance of the class by assigning it like a variable.

class Human:
	def __init__(self, first, last, age)
    	self.first = first
        self.last = last
        self.age = age
        self.fullname = first + ' ' + last
        
shawn = Human("Shawn", "McGraw", 41)
print (shawn.fullname)

More to come …