栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从类方法创建新的类实例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从类方法创建新的类实例

class Organism(object):    def reproduce(self):        #use self here to customize the new organism ...        return Organism()

另一个选项-如果

self
方法中未使用实例():

class Organism(object):    @classmethod    def reproduce(cls):        return cls()

这样可以确保生物产生更多的生物,以及(源自生物的假想的博格产生更多的博格)。

无需使用的另一个好处

self
是,除了可以从实例调用之外,现在还可以直接从类中调用它:

new_organism0 = Organism.reproduce()  # Creates a new organismnew_organism1 = new_organism0.reproduce()  # Also creates a new organism

最后,如果在方法中同时使用了实例(

self
)和类(
Organism
或从子类调用的子类):

class Organism(object):    def reproduce(self):        #use self here to customize the new organism ...        return self.__class__()  # same as cls = type(self); return cls()

在每种情况下,您都可以将其用作:

organism = Organism()new_organism = organism.reproduce()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660171.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号