Classes in Python
The ~~Beauty~~ Weirditude of Object Oriented Programming in Python
General Bits:
__main__means "this current file we're running"Classes can have variables and functions (called methods) defined within them
An Object is one instance of a Class
The data held by an Object is called an Instance Variable, and can differ from different Objects of that Class
selfrefers to the Object, not the ClassThe Strength of Classes and Objects is not needing to repeat common variables and functions, making the code DRY
Differences Between Methods and Functions:
A method must call
selfas a variableTo call the method, first call the object the method is embedded within
Methods can use variables defined elsewhere in the object
class DistanceConverter:
kms_in_a_mile = 1.609
def how_many_kms(self, miles):
return miles * self.kms_in_a_mile
converter = DistanceConverter()
kms_in_5_miles = converter.how_many_kms(5)
print(kms_in_5_miles)
# prints "8.045"The Magic of Dunder Methods
Sometimes it's a shitload easier to have code run when a new object is being created, instead of creating the object then running the object's method. For this, dunder methods -- also called magic, also called constructors. In Python, this is done with __init__, which can then have variables passed to it as the object is created.
Related is __repr__, so that when an error pops up, a more useful string is returned. This also gives the object a name, which is pretty handy. Often this can be defined as part of the intialization, but nearly any object-unique attribute will work.
Object Attributes
An object can both inherit an attribute from its class (called a class attribute), or by creating an attribute (called an instance attribute) through object.instance_attr = "foo".
Both of these are considered attributes of the object. To access object attributes:
These attribute handlers can also be run on the default data types (str, dict) and functions (count, slice).
Putting It All Together
Last updated
Was this helpful?