Classes and Objects
Table of contents:
Classes And Objects
Python is an object oriented programming language. Almost everything in Python is an object
, with its properties and methods. A class
is like an object
constructor, or a “blueprint” for creating objects.
For example:
A factory can have a blueprint of making a car for a specific model. The blueprint is a ‘class’.
Customer can buy a customized car, leather interior, roof, navigation system …etc, for that specific model. The customized car here is an object
.
Basic Python Class
In python, there are built-in data types, such as numeric (int
, float
), Boolean (True
, False
), Sequence Type (string
, list
, tuple
) and Dictionary (dict
). Python has an built-in function type()
to ascertain the data type of a certain value.
However, a custom datatype can be built by using python class.
Let’s say we want to have a Book datatype in python. We want the Book datatype contains the information of book name, publish year, author name, book price, and if it is kindle version.
Class
datatype can contain two types of variable, instance variable
and class variable
. instance variable
are used for data that is unique to each instance, such as ‘name’, ‘publish_year’, ‘author’, ‘price’, ‘is_kindle’. class variables
are the variables that are shared among all instances of a class. The example here can be ‘num_of_books’. It can be called through a class itself or an instance of a class.
All classes have a function called __init__()
, which is always executed when the class is being initiated. Use the __init__()
function to assign values to object properties, or other operations that are necessary to do when the object is being created.
Now, the __Book__
data type has been created. The next step is to instanciate the class to create an object, a book.
'How to master python'
2020
20
'Bing-Je'
False
Now, we have the first object. Let’s create another object, second book.
'The Road Ahead: Completely Revised and Up-to-Date'
True
False
A class must be instantiated in order to get the instance attribute/instance variable.
class does not inherent from a class or does not have the instance attribute/instance variable, "is_kindle"!
Using __dict__
attribute and check the current parameters that are assigined to a class or a instance.
{'author': 'Bing-Je',
'is_kindle': False,
'name': 'How to master python',
'price': 20,
'publish_year': 2020}
The __dict__
attribute only shows the instance variables when the method is called from a name space
, book1.
mappingproxy({'__dict__': <attribute '__dict__' of 'Book' objects>,
'__doc__': 'This is the comment section that you are able to access through "__doc__" attribute.',
'__init__': <function __main__.Book.__init__>,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'Book' objects>,
'num_of_books': 2,
'pass_statement': <function __main__.Book.pass_statement>})
The num_of_book
parameter, class variable
, indicates the number of instances has been instanciated for the class.
The __doc__
attribute shows the information about the class.
'This is the comment section that you are able to access through "__doc__" attribute.'
Alright, that is the basis of the python class and object.
Object Methods
Within a python class
, it can define mutiple functions as the method of an object
. When an object
is instantiated based on the class
, it is automatically assigned the functions as methods that can be used in advanced.
The methods can be categorized into three:
- Regular Method
- Regular method in a class automatically take the
instance
as the first argument - By convention, we ususally call the first argument as ‘self’
- Regular method in a class automatically take the
- Class Method
- Class method will add a decorator,
@classmethod
, on the top - The method in a class automatically take the
class
as the first argument - By convention, we ususally call the first argument as ‘cls’
- Class method will add a decorator,
- Static Method
- Static methods will add a decorator,
@staticmethod
, on the top - Static methods do not take the
instance
or theclass
as the first argument automatically - They behave just like normal functions, yet they should have some logical connection to our class.
- If a function of a class does not access the
instances
or theclass
anywhere within the function, it should be used as a static method
- Static methods will add a decorator,
There are some special methods, such as magic method, also known as dunder method. These methods allow us to emulate built-in types or implement operator overloading.
__init__()
- The
__init__
method for initialization is invoked without any call, when an instance of a class is created - It contains a collection of statements(i.e. instructions) that are executed at time of object creation
- The keyword
self
represents the instance of aclass
and binds the attributes with the given arguments
- The
__repr__
- To be an unambiguous representation of the object
- It should be used for debugging or logging
- It is meant to be seen by other developers
- This method can fix the vague object description when we use
print()
on a object
__str__()
- It is meant to be more readable representation of an object
- It is meant to be used as a display to the end-user
__add__()
- Can be set to perform addition on numbers or strings
__len__()
- It help perfrom the
len()
on objects.
- It help perfrom the
Now, we have created a new class
, Robot data type. We are ready to create instances, objects
.
'Hello, Bing!'
'Current time is 2020-09-02 20:44:05.000624'
'Today is Monday!'
Getter, Deletor and Setter
The property decorator
using as a getter
allows us to define Class methods that we can access like attributes. Here we have the .id()
method to be access as an attribute.
Bing's alexa
The property decorator
can be used as a deleter
to delete the instance attributes.
Delete Name
None's None
None
None
The property decorator
can be also used as a setter
in order to update the instance attribute.
Bing
alexa
Dunder Methods
With the __repr__()
and __str__()
set in the class, we can have the unambiguous representation of the object. __add__()
help perform the string addtion of instance attributes. __len__()
special dunder method help perfrom the len()
on objects.
'alexa - Bing - 08/15'
'siri - Bing-Je - 12/30'
BingBing-Je
5
4
Class Variable and Instance Variables
class variable
can be assigned to an instance through methods. Calling a class variable
will not assign the class variable
as an attribute of the instance.
{'birth': '08/15',
'ownername': 'Bing',
'robotname': 'alexa'}
The class variable has not been assigned to the instance attributes for alexa
object.
60
{'battery_amt': 60,
'birth': '08/15',
'ownername': 'Bing',
'robotname': 'alexa'}
Now, A new instance attribute, battery_amt, has been added for alexa
object through accessing the class variable.
# The class variable
can be changed through a class method.
50
The battery_amt
is a class variable with e default setting as 50. Using a class method, set_battery to change the default value to 30.
30
{'battery_amt': 60,
'birth': '08/15',
'ownername': 'Bing',
'robotname': 'alexa'}
# Using a class method
from an instance will not only update the class variable
but also that instance attribute
.
60
{'battery_amt': 60,
'birth': '08/15',
'ownername': 'Bing',
'robotname': 'alexa'}
60
# Using class method
as an alternative constructor to create multipe objects/instances
60
{'birth': '01/25', 'ownername': 'JJ', 'robotname': 'rbt'}
Static Methods
staticmethods
do not pass any instance or class, meaning it does not access an instance or a class anywhere within a function. Call a staticmethod
from a class.
4
Class Inherent
A class
can inherent the attribute and method from the other class
, parent class. Let’s say we want to create an advance robot to have advanced functions or improved functions. Here, we are going to create a new class
, AdvancedRobot data type. The AdvancedRobot data type can not only have the basic functions that a Robot object
has but also have advanced functions such as playing music and reporting the location.
super().__init__()
or parent_class.init__(self,)
from the init method of a subclass to call the parent init method to inherits the instance attributes.
Python will look for the chain of the inheritence to get what is inherited from the parent class. This chain is called method resolutional order. The help()
can help visualize the method resolutional order in this case.
Help on class AdvancedRobot in module __main__:
class AdvancedRobot(Robot)
| Method resolution order:
| AdvancedRobot
| Robot
| builtins.object
|
| Methods defined here:
|
| __init__(self, robotname, ownername, birth, location)
| Initialize self. See help(type(self)) for accurate signature.
|
| play_music(self)
|
| tell_me_time(self)
| # change the output of time for differencing from Robot class
|
| where_am_I(self)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| battery_amt = 65
|
| ----------------------------------------------------------------------
| Methods inherited from Robot:
|
| __add__(self, other)
|
| __len__(self)
|
| __repr__(self)
| Return repr(self).
|
| __str__(self)
| Return str(self).
|
| charge_battery(self, amount)
| # method can access a class variable as an attribute of an instance; regular method
|
| say_hello(self)
| # saying hello with user name; regular method
|
| what_day_is_today(self)
| # return what day is today randomly; regular method
|
| ----------------------------------------------------------------------
| Class methods inherited from Robot:
|
| from_string(robot_string, separator) from builtins.type
| robot_string: 'robotname-onwername-mm/dd' ; separator : '-'
|
| set_battery(amount) from builtins.type
|
| ----------------------------------------------------------------------
| Static methods inherited from Robot:
|
| lucky_number_1_to_10()
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Robot:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| id
None
By creating a new instance, we can prove that the AdvancedRobot object
has perfect inherented everything from Robot class
.
65
{'birth': '08/15',
'locattion': 'living room',
'ownername': 'BingJe',
'robotname': 'google'}
The class variable has not been assigned to the instance attributes for google object.
75
{'battery_amt': 75,
'birth': '08/15',
'locattion': 'living room',
'ownername': 'BingJe',
'robotname': 'google'}
Now, A new instance attribute, battery_amt, has been added for google object through accessing the class variable.
Current time is 02:28:13.928534
'Today is Sunday!'
Playing music ...
{'birth': '08/15',
'ownername': 'BingJe',
'robot_list': [],
'robotname': 'javis'}
The robot managing list is empty. Use the regular methods to update the managing list.
Robot: Alexa ; Owner: Bing
Robot: Siri ; Owner: Bing-Je
Robot: Google ; Owner: BingJe
Robot: Alexa ; Owner: Bing
Robot: Google ; Owner: BingJe
Built-in Functions
isinstance()
can check if an object is an instance.
issubclass()
can check if a subclass is of another class.
True
True
Application
Multiple Choice Question Application
'What color are bananas?\n(a) Teal\n(b) Magneta\n(c) Yellow\n\n'
What color are apples?
(a) Red/Green
(b) Purple
(c) Orange
a
What color are bananas?
(a) Teal
(b) Magneta
(c) Yellow
b
What color are strawberries?
(a) Yellow
(b) Red
(c) Blue
c
You got 2 question(s) wrong ! Sorry :(
What color are apples?
(a) Red/Green
(b) Purple
(c) Orange
a
What color are bananas?
(a) Teal
(b) Magneta
(c) Yellow
c
What color are strawberries?
(a) Yellow
(b) Red
(c) Blue
b
You got 3 questions right ! Congrats !!
Reference: