December 2018
Beginner to intermediate
796 pages
19h 54m
English
Class methods are slightly different from static methods in that, like instance methods, they also take a special first argument, but in this case, it is the class object itself. A very common use case for coding class methods is to provide factory capability to a class. Let's see an example:
# oop/class.methods.factory.pyclass Point: def __init__(self, x, y): self.x = x self.y = y @classmethod def from_tuple(cls, coords): # cls is Point return cls(*coords) @classmethod def from_point(cls, point): # cls is Point return cls(point.x, point.y)p = Point.from_tuple((3, 7))print(p.x, p.y) # 3 7q = Point.from_point(p)print(q.x, q.y) # 3 7
In the preceding code, I showed you how to use a class method to create a factory for the class. ...
Read now
Unlock full access