python-class
Class
Python class is more like C++ class, it supports inheritance, function overridden (not like C++, if you create an instance of child class, you never see parent's method if child defines method with same name even different signature(argument list)
), operator overload, static method etc.
Overloading vs Overriding
Overloading occurs when two or more methods in one class have the same method name but different parameters
.
Overriding occurs when two methods have the same method name and parameters
. One of the methods is in the parent class, and the other is in the child class. Overriding allows a child class to provide the specific implementation of a method that is already present in its parent class
basic rules
"_"
is used to indicate that it should be used in a private context, but still can be accessed outside of class- prefix
__show two underscores
for private user defined, NO accessable outside of class, exception happens when accesses it. - prefix
__len__
for built-in attr, but accessable outside of class - no prefix for public attribute
def __init__(self)
is not need if nothing in itchild must call super().__init__() only if parent needs input
self
can be other name, but it has to be the first parameter of any function in the classdel instance
parameter can be class type or other built-in type as well
1 | def fun_parm_types(fun_n, class_n): |
- Always use composition not inheritance for python class
1 | class CA: |
google
hello
google
'CA' object has no attribute '__show'
'CA' object has no attribute '__group'
dynamic attribute
There is one special feature for python that is different from C++, you can add attribute dynamically
that means you can add attribute anytime you want to a class or an instance
, but it’s not a good habit
as others do not know that attribute at all.
by default you can add any attribute to an instance, but you can restrict it by __slots__
, but restriction only applies on instance not class.
1 | class CA: |
12
13
add new attr not in __slots__, exception happened
function overloading/overriding
1 | class person: |
I eat from person
after eat from student
i eat apple from teacher
operator overloading
In some case, you may want to access user defined class like other built-in type
, like len(user_class_instance), user_class_instance[0]
what you need to do is to implement special functions
, here are a list for such special functions.
built-in function(descriptor)
1 | - len __len__ |
operator
p1 + p2 | __add__ |
---|---|
p1 - p2 | __sub__ |
*,/,// | __xx__ |
p1 % p2 | __mod__ |
<<,>> | __xx__ |
p1 < p2 | __lt__ |
>, <=, >, >= | __le__, __gt__, __ge__ |
1 | class Phone: |
1 | import sys |
'Apple'
1 | print(len(ph1)) |
5
setattr/getattr/hasattr/delattr with class
Most of time, class attribute(include function) is defined when defines a class, so we know the name of it, hence we can access it by class_instance.name or class_instance.get_name()
, but there are times when you might not know the name of a attribute until runtime as some of them defined by setattr at runtime!!!
, that’s where hasattr and getattr
(as well as delattr and setattr) come into play.
1 | # must quote attribute |
1 | class Foo: |
all attributes(not include function) for instance are stored at instance._dict__= {'name': 'jason'}
class instance doesn't have id, use default value 123
f1.get_name return jason
staticmethod and classmethod
staticmethod
staticmethod is used to group functions
which have some logical connection within a class
. it knows nothing about the class or instance it was called on, It just gets the arguments that were passed, no self argument, just group functions in a class. but it can be called by class or instance as well.
1 | Class.staticmethod() # class directly |
It is basically useless in Python you can just use a module function instead of a staticmethod
classmethod
A classmethod is a method that is bound to a class rather than its object
. It doesn't require creation of a class instance
, much like staticmethod.
The differences between a static method and a class method are:
- Static method knows
nothing
about the class and just deals with the parameters - Class method
works with the class
since its first parameter is always the class type.
The class method can be called both by the class and its object, both pass class type as first parameter
.
1 | Class.classmethod() # class directly |
But no matter what, the class method is always attached to a class with first argument as the class itself cls
.
1 | # cls is class type!!! |
This is useful when you want a method to be a factory for the class
1 | class Student: |
2 2
<class '__main__.Student'>
<class '__main__.Student'>
3 4
<__main__.Student object at 0x7f5e5d055df0>
<class '__main__.Student'>
setter/getter
setter/getter provide a way that you can access/modify attribute with obj.name
but the implementation behind it is a function, this is very useful in some case, let’s say your old application writing code with obj.name
, but after several years, you want to /need to return value depends on more logic, but without changing user code
, getter
comes into play.
1 | class Student: |
setting name jason
getting name
jason
enum class
enum is used to group literal together, so that you can use them from class, more specific for its purpose
1 | from enum import Enum |
Month.Jan