-
Notifications
You must be signed in to change notification settings - Fork 0
Python Class Basics
James Small edited this page Apr 8, 2018
·
3 revisions
- Also - Basic python class overview/walk through
- Also - Difference between a python class and a class instance
# Class names should be Capitalized!
# Think of a Python class as a factory - it produces instances
# The class definition is the template for what's in the instances
class Mywidget:
# Class level variable - overly simplistic example
counter = 0
# Methods or functions in the class always have "self" as an argument by convention
# "self" represents an instance of the class
# __init__ is used to initialize a class instance
# In this case, we also require the argument "name". If "message" is passed in
# we'll use that too, otherwise we default to None (empty).
def __init__(self, name, message=None):
# These are instance variables - they're local to each instance
self.name = name
self.message = message
# This is a class variable, it is shared by all instances or
# more accurately, inherited by them
Mywidget.counter += 1
def talk(self):
if self.message:
print(self.message)
# self.message is None
else:
print('I have nothing to say!')
# Start the python shell/REPL:
> python
>>> # Paste in above class code
# The class by itself isn't that useful:
>>> Mywidget
<class '__main__.Mywidget'>
# The class method (embedded function) talk expects an instance
# This is because is defined it to expect the argument self
>>> Mywidget.talk()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: talk() missing 1 required positional argument: 'self'
talk() missing 1 required positional argument: 'self'
# Class level variables can be accessed directly and don't require an instance:
>>> Mywidget.counter
0
# Create an instance of the class:
>>> widget1 = Mywidget('Alpha')
# From the instance we can now invoke the class method:
>>> widget1.talk()
I have nothing to say!
# We can also invoke class methods by passing in the instance as an argument:
>>> Mywidget.talk(widget1)
I have nothing to say!
# In this case below, the instance is passed in implicitly:
>>> widget1.talk()
I have nothing to say!
# Here, the widget1 instance inherits the talk method from the Mywidget class. When the
# talk method is invoked, widget1 is implicitly passed in as the instance (self argument).
# By default, if you print/display a class instance, you get the module name, the class
# name, and the object address location:
>>> widget1
<__main__.Mywidget object at 0x04432ED0>
# __main__ is the module, in this case it represents our interactive Python session
# What's generally more useful is if you override or overload the defaults and instead
# show a more meaningful representation of the instance. One way to do that is by
# defining a __repr__ method in the class:
def __repr__(self):
return '<{}: name={}, message={}>'.format(
Mywidget.__name__, self.name, self.message)
# If we go back and redefine the class with this method added, when we display an
# instance we get back more useful data. Note - we must recreate the instance since
# we redefined the class:
>>> widget1 = Mywidget('Alpha')
>>> widget1
<Mywidget: name=Alpha, message=None>
# Every time we invoke (call) a class, we create an instance:
>>> widget2 = Mywidget('Beta', 'I am the loquacious one!')
>>> Mywidget('Gamma', 'I am lost - no variable name references my instance object!')
<Mywidget: name=Gamma, message=I am lost - no variable name references my instance object!>
# If we check, we can see three instances of our class have been created
>>> Mywidget.counter
3
# Can we invoke (call) an instance by default? Let's try:
>>> widget1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Mywidget' object is not callable
'Mywidget' object is not callable
# Why can we invoke a class but not an instance (by default)? Because invoking a class
# creates an instance. To be able to invoke an instance, we would have to define a
# callable method - as a quick example, we could add this to the above class definition:
def __call__(self):
print('I am invokable!')
# Then after recreating the instance based on the new class definition, we could invoke
# it:
>>> widget3 = Mywidget('Delta', 'Run me!')
>>> widget3()
I am invokable!
class Mywidget:
# Class level variable
counter = 0
# class initialization
def __init__(self, name, message=None):
# These are instance variables - they're local to each instance
self.name = name
self.message = message
# This is a class variable, it is shared by all instances or
# more accurately, inherited by them
Mywidget.counter += 1
# class method
def talk(self):
if self.message:
print(self.message)
# self.message is None
else:
print('I have nothing to say!')
# overload/override magic method to handle class display/printing
def __repr__(self):
return '<{}: name={}, message={}>'.format(
Mywidget.__name__, self.name, self.message)
# overload/override magic method to allow invoking instances
def __call__(self):
print('I am invokable!')
Questions/Problems? Well then, please open an issue!
Note: Tested on Windows 7 using Python 3.6