[] Data structure based 01-Python

New knowledge points record encountered in the learning process

1, you do not add the brackets when defining python class?

In Python2, the need for object inheritance is explicitly written as FrenchDeck (object);
and In Python 3, this inheritance is the default, it can be added from time plus, plus, then object can not write write.

2, properties of the class

And similar variables python, which attributes do not have explicit description of the object is automatically created when assignment.

3, information hiding

For complex abstraction, information hiding meaning is important for some languages for this purpose set up a special mechanism, there is no internal python serve the needs of such a mechanism, we can only rely on some programming conventions. For example:
3.1 to underscore property or method are used as the inside, outside the class should not be called.
3.2 starts with a double underscore, but not in the name of ending underscore two to do a special deal so that the outer class is not called.

4, static methods

There is no essential link with the class definition, but can such services, the parameter list should not have self, the need to add a function modifier @staticmethod.

5, special methods

If the class need to define special methods, for example, +, -, *, /, etc. operations, require special method name in the class, e.g. __add __ (Self, OTHER), Sub , MUL , MOD , floordiv , truediv
Druediv: is / Floating division point
Floordiv: // is divisible operator

Added:
1, comparison of the relationship special method:
equal: _ EQ _, _ NE _
greater than: _ gt _, _ GE _
less than: _ lt _, _ Le _
2: output into a string, so that outside the class when using the print function, the special method automatically called.
_ DEF STR _ (Self):
the Print ( '-')

6, example code

class Rational():
    """有理数类进阶"""
    def __init__(self, num, den=1):
        if not isinstance(num, int) or not isinstance(den, int):
            raise TypeError
        if den == 0:
            raise ZeroDivisionError

        sign = 1
        if num < 0:
            sign, num = -sign, -num
        if den < 0:
            sign, den = -sign, -den

        g = Rational._gcd(num, den)  # 求最大公约数

        self._num = sign * (num // g)
        self._den = (den // g)

    @staticmethod  # 为这个类服务,但是实际上和这个类无关的方法
    def _gcd(m, n):  # 求最大公约数的算法
        if n == 0:
            n, m = m, n
        while m != 0:
            m, n = n % m, m
        return n

    def num(self): return self._num

    def den(self): return self._den

    def __add__(self, other):  # other 相当于处在类外,按照约定不要直接访问其属性,而是通过接口
        """定义加法运算的例子,其他运算类似"""
        if isinstance(other, Rational):
            num = self._num * other.den() + self._den * other.num()
            den = self._den * other.den()
            return Rational(num, den)
        else:
            raise TypeError

    def __gt__(self, other):
        """定义比较大小的例子,其他关系可以类似定义"""
        return self._num * other.den() > self._den * other.num()

    def __str__(self):
        return str(self._num) + '/' + str(self._den)
        

a = Rational(3, 4)
b = Rational(4, 5)

if __name__ == '__main__':
    print(a + b)
    print(a > b)
    print(Rational._gcd(5, 10))

输出:
    31/20
    False
    5

Summary: class init property is defined in the following definition of the relevant methods, interfaces are given access attributes, str output using a special method. The following is an iterative process: definition and access, operation and output.

# End, refueling, refueling, refueling.

Published 20 original articles · won praise 0 · Views 676

Guess you like

Origin blog.csdn.net/weixin_43522964/article/details/104551792