A Pythonic Object
Lets start by introducing a Vector
class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
An alternative constructor
Since in above example, we export a Vector2D
as bytes;
we also need a method to imports a vector2D
from binary sequence.
Looking at the standard library for inspiration, we see that array.array
has a class method frombytes()
. Lets adopt this nomenclature in our Vector2D
class.
1 2 3 4 5 6 7 8 |
|
@classmethod v/s @staticmethod
@classmethod
:
- It is used to define a method that operates on class; not on instances.
- It receives the class itself as the 1st argument (eg.
cls
in above code) instead of an instance (eg.self
) - Most commonly used as alternate constructors (eg.
frombytes
in above code) Note: (in the abovefrombyytes()
) how the last line infrombytes()
usescls
argument by invoking it to build a new instance (cls(*memv)
) - By convention the 1st argument of the
@classmethod
should be namedcls
(but Python does not care about the name though)
@staticmethod
A static method is just like a plain old function that happens to live inside the body of a class instead of being defind outside the class. It does not have access to internal state variables of the class or the instance. It is kept inside the class definition to provide easy access to related functions/method, so the user have access to all necessary method for a class within itself instead of finding it elsewhere.
An example:
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 |
|
Formatted displays
int
type supportsb
(for base=2 integers) andx
(for base=16 integers).float
type implementsf
(for fixed-points) and%
(for a percentage display).
1 2 3 4 5 6 7 8 |
|
format_spec
argument as it likes.
1 2 3 4 |
|
__format__()
method, the method inherited from object
return str(my_object)
.