美文网首页
子类父类

子类父类

作者: 手捧樱花v | 来源:发表于2022-02-08 23:18 被阅读0次
    class Entity():
    
        def __init__(self,object_type):
            print("parent class init called")
            self.object_type = object_type
    
        def get_context_length(self):
            raise Exception('get_context_length not implemented')
    
        def print_title(self): //子类直接调用父类方法
            print(self.title)
    
    class Document(Entity):
    
        def __init__(self,title,author,context):
            print("Document class init called")
            Entity.__init__(self,'document')
            self.title = title 
            self.author = author 
            self.__context = context
    
        def get_context_length(self):
            return len(self.__context)
    
    class Video(Entity):
    
        def __init__(self, title,author,video_length):
            print("Video class init is called")
            Entity.__init__(self,'video') //显示调用父类属性
            self.title = title
            self.author = author
            self.__video_length = video_length
    
        def get_context_length(self):
            return self.__video_length
    
    
    harry_potter_book = Document('Harry Potter(Book)', 'J. K. Rowling', '... Forever Do not believe any thing is capable of thinking independently ...')
    # harry_potter_movie = Video('Harry Potter(Movie)', 'J. K. Rowling', 120)
    print(harry_potter_book.object_type)
    # print(harry_potter_movie.object_type)
    harry_potter_book.print_title()
    # harry_potter_movie.print_title()
    # print(harry_potter_book.get_context_length())
    # print(harry_potter_movie.get_context_length())
    
    a= 3
    def b(a):
        print(a)
        print(id(a))
        a = a+1
        print(id(a))
    b(a)
    
    l = 1
    def multiply_2(l): 
        print(id(l))
        l=2
        #for index in range(0, len(l)): l[index] *= 2 
        print(id(l)) 
        return l
    
    # print(id(l))  
    multiply_2(l)
    # print(l) 
    
    int不可变,内存地址变;list可变,内存地址不变 :新开辟内存空间,值不会变
    

    抽象类,加上@abc.abstractmethod装饰器后严格控制子类必须实现这个方法

    from abc import ABCMeta,abstractmethod
    
    class Entity(metaclass=ABCMeta):
    
        @abstractmethod
        def get_title(self):
            pass
    
        @abstractmethod
        def set_title(self):
            pass
    
    class Document(Entity):
    
        def get_title(self):
            return self.title
    
        def set_title(self,title):
            self.title = title
    
    document = Document()
    document.set_title("Harrie Potter")
    print(document.get_title())
    
    # 抽象类就是这么一种存在,它是一种自上而下的设计风范,你只需要用少量的代码描述清楚要做的事情,定义好接口,然后就可以交给不同开发人员去开发和对接。
    

    相关文章

      网友评论

          本文标题:子类父类

          本文链接:https://www.haomeiwen.com/subject/owiikrtx.html