0%

Advanced Object-Oriented

Python Decorator

Naming a property starting with a single underscore implies that the property is protected and is not recommended for direct access, so if you want to access the property, you can do so using the getter and setter methods of the property. To do this, consider using the @property wrapper to wrap getter and setter methods to make access to properties secure and convenient, as shown below.

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
31
32
33
34
35
36
37
38
class Person(object):

__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
self._age = age

# accessor - getter function
@property
def name(self):
return self._name

# accessor - getter function
@property
def age(self):
return self._age

# modifier - setter function
@age.setter
def age(self, age):
self._age = age

@staticmethod
def is_age_valid(age):
# the oldest people in records
return age < 123

@classmethod
def now(cls):
ctime = localtime(time())
return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec)

def main():
person = Person('Jesse', 22)
# dynamic binding for __slots__
# person._height = 180
# AttributeError: 'Person' object has no attribute 'height'
person._gender = "male"
__slots__ for dynamic binding

Python is a dynamic language. In general, dynamic languages allow us to bind new properties or methods to an object while the program is running, as well as unbind already bound properties and methods. However, if we need to qualify an object of a custom type to bind only certain properties, we can qualify it by defining a variable called __slots__ in the class. It is important to note that the limitation of __slots__ only applies to the object of the current class and does not apply to subclasses. The example presents above.

Static method

Static method belongs to class rather than objects. The example presents above. @staticmethod

Class method

Python class methods defined in the class, class method called the first parameter named “cls”, it represents the current class related information of the object (the class itself is an object, some places also called metadata object of a class), we can get through this parameters and related information and can create the object of the class, the code is shown above. @classmethod

Poly-Morphism

A subclass that inherits a parent class’s methods can give a new implementation version of the parent class’s existing methods, an action called method override. By method override we can make the same behavior of the parent class have different versions of the implementation in the subclass, and when we call this subclass override method, the different subclass objects behave differently, and this is polymorphic.

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
from abc import ABCMeta, abstractmethod

class Pet(object, metaclass=ABCMeta):

def __init__(self, nickname):
self._nickname = nickname

@abstractmethod
def make_voice(self):
pass

class Dog(Pet):

def make_voice(self):
print('%s: wahwah...' % self._nickname)

class Cat(Pet):

def make_voice(self):
print('%s: miao...miao...' % self._nickname)

def main():
pets = [Dog('Wangcai'), Cat('Katty'), Dog('Yellow')]
for pet in pets:
pet.make_voice()

if __name__ == '__main__':
main()

In the above code, we treated the Pet class as an abstract class. An abstract class is a class that cannot create an object, but exists only to allow other classes to inherit it. Python doesn’t support abstract classes syntactically like Java or C# does, but you can use the ABCMeta meta-class of the ABC module and the abstractmethod wrapper to achieve the effect of abstract classes. If an abstractmethod exists in a class, the class cannot be instantiated (creating objects). In the code above, the Dog and Cat subclasses rewrite the make_voice abstract method in the Pet class and give different versions of the implementation, and when we call the method in the main function, the method behaves polymorphic (the same method does different things).

The content of this blog is concluded from Jackfrued’s GitHub. Thank you.