Skip to main content
 首页 » 编程设计

python之难以理解类方法

2025年01月19日8birdshome

class Book: 
    def __init__(self,title,author): 
        self.title = title 
        self.author = author 
 
    def __str__(self): 
        return '{} by {}'.format(self.title,self.author) 
 
 
class Bookcase: 
    def __init__(self,books=None): 
        self.books = books 
 
    @classmethod 
    def create_bookcase(cls,book_list): 
        books = [] 
        for title,author in book_list: 
            books.append(Book(title,author)) 
        return cls(books) 

大家好。我试图了解类方法在上面的以下情况中是如何工作的。

When we return cls(books), does the __init__ method get called to return an instance of the classes books (cls.books instead of self.books)

或

does returning cls(books) not have anything to do with using the init method and returning self.books?

请您参考如下方法:

内部create_bookcase , 那cls(books)确实调用了 __init__方法。*

但是,它调用了 __init__ cls的方法| , 而不是 __init__ Bookcase的方法| .

有什么区别?

class StoreBookcase(Bookcase): 
    def __init__(self, book_list, backstock=None): 
        super().__init__(book_list) 
        self.backstock = backstock if backstock else [] 

现在如果我调用 StoreBookcase.create_bookcase , 当它这样做时 cls(books) , 那cls是StoreBookcase .

当然StoreBookcase可能想要覆盖 create_bookcase采取可选的backstock范围。但是在子类中没有额外参数的情况下,或者当您对默认值满意时,您可以只使用基类的 classmethod。像这样。所以,classmethod s 可用于为整个层次结构创建“替代构造函数”。


* 从技术上讲,它称为 __new__方法; __init__仅在 __new__ 时被调用返回 cls 的实例,或者当然,如果您明确调用它。但是大多数类只使用 object.__new__ , 它返回 cls 的一个实例, 所以 __init__被调用。