Python---class

Base

class Document():
    def __init__(self, title, author, context):
        print("Run init function.")
        self.title = title
        self.author = author
        self.__context = context    #私有属性
    
    def get_context_length(self):
        return len(self.__context)

    def intercept_context(self, length):
        self.__context = self.__context[:length]

def main():
    harrypotter_book = Document("Harry Potter", "J. K. Rowling", \
                                "... Forever Do not believe any thing is capable of thinking independently ...")
    
    print(harrypotter_book.title)
    print(harrypotter_book.author)
    print(harrypotter_book.get_context_length())

    harrypotter_book.intercept_context(10)

    print(harrypotter_book.get_context_length())

if __name__ == "__main__":
    main()

对于类内的变量,无论在类定义中还是类的创建函数中,实例函数需要使用,都要加self:

class Document():
    cls_var = "class variable"
    def __init__(self, param1):
        self.param1 = param1

    def show_var(self):
        print(self.cls_var)
        print(self.param1)

def main():
    cls1 = Document("haha")
    cls1.show_var()

if __name__ == "__main__":
    main()

类函数,静态函数

例子1,变量访问:

class Document():
    cls_var = "class variable"
    def __init__(self, param1):
        self.param1 = param1

    def show_var(self):
        print(self.cls_var)

    def set_var(self, param):
        self.cls_var = param

    @classmethod
    def show_cls_var(cls):
        print(cls.cls_var)

    @classmethod
    def set_cls_var(cls):
        cls.cls_var = "new class variable"

    @staticmethod
    def show_static_var():
        print(Document.cls_var)

def main():
    test = Document("hehe")

    test.set_cls_var()
    test.show_var()
    test.show_cls_var()
    test.show_static_var()
    test.set_var("instance variable")

if __name__ == "__main__":
    main()

静态变量 cls_var 想要改变并对所有类实例起作用,要通过类的类函数和静态函数来改变,实例内的赋值只会影响本实例.
例子2, 类继承:

class Document():
    X = 1
    Y = 2

    def param_add(self, a, b):
        return a + b

    @classmethod
    def class_method(cls):
        return cls.param_add(cls.X, cls.Y)

    @staticmethoduper().__init__()
    def static_method():
        return Document.param_add(Document.X, Document.Y)

class SubDocument(Document):
    X = 5
    Y = 7


def main():
    test1 = Document()
    print(test1.class_method())
    print(test1.static_method())
    
    test2 = SubDocument()
    print(test2.class_method())
    print(test2.static_method())

if __name__ == "__main__":
    main()

类继承

class Document():

    def __init__(self):
        self.a = 0
        self.b = 0

    def set_param(self, a, b):
        self.a = a
        self.b = b

    def param_add(self):
        return self.a + self.b

class SubDocument(Document):

    def __init__(self):
        super().__init__()

    def use_super_fun(self):
        return self.param_add()

def main():
    test1 = Document()
    test1.set_param(1, 2)
    print(test1.param_add())

    test2 = SubDocument()
    test2.set_param(5, 7)
    print(test2.use_super_fun())

if __name__ == "__main__":
    main()

类方法重写

class Document():

    def __init__(self):
        self.a = 0
        self.b = 0

    def set_param(self, a, b):
        self.a = a
        self.b = b

    def param_add(self):
        return self.a + self.b

class SubDocument(Document):

    def __init__(self):
        super().__init__()

    def use_super_fun(self):
        return self.param_add()

    def param_add(self):
        return self.a * self.b

def main():
    test1 = Document()
    test1.set_param(1, 2)
    print(test1.param_add())

    test2 = SubDocument()
    test2.set_param(5, 7)
    print(test2.param_add())

if __name__ == "__main__":
    main()

抽象类

用于团队开发,定义接口,测试使用

import numpy as np
from abc import ABCMeta, abstractmethod

class Entity(metaclass=ABCMeta):
    @abstractmethod
    def show_detail(self):
        pass
    
    @abstractmethod
    def param_add(self, a, b):
        pass

class Document(Entity):
    def show_detail(self):
        print("类实例")        

    def param_add(self, a, b):
        return a + b

def main():
    test = Document()
    test.show_detail()
    print(test.param_add(1, 2))

if __name__ == "__main__":
    main()

菱形继承

C3算法用于防止多次初始化,详细见 https://blog.csdn.net/u011467553/article/details/81437780

class A():
    def __init__(self):
        print('enter A')
        print('leave A')

class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')

class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')

class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')

D()

输出是:

enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D

你可能感兴趣的:(Python---class)