静态函数/类函数

类函数实现不同的init构造函数

class Document:
    WELCOME_STR = "welcomee! the context for this book is {}"

    def __init__(self,title,author,context):
        print("init function called")
        self.title = title
        self.author = author
        self.__context = context

    @classmethod
    def create_empty_book(cls,title,author):
        return cls(title=title,author=author,context='nothing')

    @classmethod
    def sakura(cls,title,author):
        return cls(title=title,author=author,context="sakura")

    def get_context_length(self):
        return self.__context

    @staticmethod
    def get_welcome(context):
        return Document.WELCOME_STR.format(context)

empty_book = Document.create_empty_book('What every man thinks about aprt from sex','professor sheridan simove')
print(empty_book.get_context_length())
print(empty_book.get_welcome('indeed nothing'))

saku = Document.sakura('sakura1','sakura2')
print(saku.get_context_length())
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容