热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从类方法创建新的类实例-Createnewclassinstancefromclassmethod

Iwanttobeabletocreateanewinstanceofanobjectbycallingamethodonanalreadyinstantiat

I want to be able to create a new instance of an object by calling a method on an already instantiated object. For example, I have the object:

我希望能够通过调用已实例化的对象上的方法来创建对象的新实例。例如,我有对象:

organism = Organism()

有机体=有机体()

I want to be able to call organism.reproduce() and have two objects of type Organism. My method at this point looks like this:

我希望能够调用organism.reproduce()并拥有两个类型为Organism的对象。我的方法在这一点看起来像这样:

class Organism(object):
    def reproduce():
        organism = Organism()

and I'm pretty sure it doesn't work (I'm not really even sure how to test it. I tried the gc method in this post). So how can I make my object create a copy of itself that's accessible just like the first object I created (with organism = Organism())?

而且我很确定它不起作用(我甚至不确定如何测试它。我在这篇文章中尝试了gc方法)。那么我怎样才能让我的对象创建一个可以访问的副本,就像我创建的第一个对象一样(使用organism = Organism())?

5 个解决方案

#1


34  

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

Another option -- if the instance (self) isn't used within the method:

另一个选项 - 如果在方法中未使用实例(self):

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

This makes sure that Organisms produce more Organisms and (hypothetical Borgs which are derived from Organisms produce more Borgs).

这确保了生物体产生更多的生物体(假设的生物体来源于生物体产生更多的生物体)。

A side benefit of not needing to use self is that this can now be called from the class directly in addition to being able to be called from an instance:

不需要使用self的附带好处是,除了能够从实例调用之外,现在可以直接从类中调用它:

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

Finally, if both the instance (self) and the class (Organism or subclasses if called from a subclass) are used within the method:

最后,如果在方法中使用实例(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()

In each case, you'd use it as:

在每种情况下,您都将它用作:

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

#2


3  

why not simply use the copy module?

为什么不简单地使用复制模块?

import copy
organism = Organism()
replica = copy.deepcopy(organism)

#3


2  

What about something like this:

这样的事情怎么样:

class Organism(object):

    population = []

    def __init__(self, name):
        self.name = name
        self.population.append(self)
    def have_one_child(self, name):
        return Organism(name)
    def reproduce(self, names):
        return [self.have_one_child(name) for name in names]

Result:

>>> a = Organism('a')
>>> len(Organism.population)
1
>>> a.reproduce(['x', 'y', 'z']) # when one organism reproduces, children are added
                                 # to the total population
                                 # organism produces as many children as you state
[<__main__.Organism object at 0x05F23190>, <__main__.Organism object at 0x05F230F0>, <__main__.Organism object at 0x05F23230>]
>>> for ele in Organism.population:
...     print ele.name
... 
a
x
y
z
>>> Organism.population[3].reproduce(['f', 'g'])
[<__main__.Organism object at 0x05F231D0>, <__main__.Organism object at 0x05F23290>]
>>> for ele in Organism.population:
...     print ele.name
... 
a
x
y
z
f
g

#4


1  

The same way you did originally, but then you have to do something with it!

就像你原来做的那样,但是你必须用它做点什么!

organism = Organism() calls the class Organism (parentheses directly after a name is the "call" operation). This creates and returns a new instance of the class, which you then bind to the name organism.

有机体=有机体()调用类有机体(名称后面的括号是“调用”操作)。这将创建并返回该类的新实例,然后将其绑定到名称有机体。

When you execute that line in the interpreter, you now have a variable organism referring to the new Organism instance you just created.

当您在解释器中执行该行时,您现在有一个变量有机体引用您刚创建的新的有机体实例。

When you write that line inside a function (including a method, because there's no difference between a method and a function "from the inside"), it does the same thing, but the variable organism is a local variable. Local variables are thrown away when the function is finished, so this does create a new Organism instance, but it doesn't achieve anything because you never gain access to it.

当你在函数中写入那一行时(包括一个方法,因为方法和函数之间没有“内部”),它做同样的事情,但变量有机体是一个局部变量。函数完成时会丢弃局部变量,因此这会创建一个新的Organism实例,但它无法实现任何功能,因为您永远无法访问它。

Your function should return any information it wants to communicate to its caller. Any local variables that you don't return are only useful if you use those variables to create something you do return.

您的函数应该返回它想要与其调用者通信的任何信息。您不返回的任何局部变量仅在您使用这些变量创建返回的内容时才有用。

Note that this has nothing to do with your particular problem of creating an instance inside a method; it's just how functions/methods work in general. You will need to learn how functions work before you can successfully write object-oriented programs using classes and instances; I would strongly suggest you work through some tutorials.

请注意,这与在方法中创建实例的特定问题无关;它只是函数/方法的一般工作方式。在使用类和实例成功编写面向对象的程序之前,您需要了解函数的工作原理;我强烈建议你完成一些教程。

#5


0  

from copy import copy                                                           

class Organism(object):                                                         

    def __init__(self,name):                                                    
        self.name=name                                                          

    def setName(self,name):                                                     
        self.name=name                                                          

    def reproduce(self,childname):     
        #use deepcopy if necessary                                         
        cp = copy(self)                                                         
        cp.setName("descendant from " + self.name + " " + childname)            
        return cp                                                               

    def __str__(self):                                                          
        return self.name                                                        

first = Organism("first")                                                       
secOnd= first.reproduce("second")                                              

print first                                                                     
print second 

推荐阅读
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • Java中包装类的设计原因以及操作方法
    本文主要介绍了Java中设计包装类的原因以及操作方法。在Java中,除了对象类型,还有八大基本类型,为了将基本类型转换成对象,Java引入了包装类。文章通过介绍包装类的定义和实现,解答了为什么需要包装类的问题,并提供了简单易用的操作方法。通过本文的学习,读者可以更好地理解和应用Java中的包装类。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • Whatsthedifferencebetweento_aandto_ary?to_a和to_ary有什么区别? ... [详细]
  • 本文介绍了Java中Currency类的getInstance()方法,该方法用于检索给定货币代码的该货币的实例。文章详细解释了方法的语法、参数、返回值和异常,并提供了一个示例程序来说明该方法的工作原理。 ... [详细]
  • 十大经典排序算法动图演示+Python实现
    本文介绍了十大经典排序算法的原理、演示和Python实现。排序算法分为内部排序和外部排序,常见的内部排序算法有插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。文章还解释了时间复杂度和稳定性的概念,并提供了相关的名词解释。 ... [详细]
  • Python使用Pillow包生成验证码图片的方法
    本文介绍了使用Python中的Pillow包生成验证码图片的方法。通过随机生成数字和符号,并添加干扰象素,生成一幅验证码图片。需要配置好Python环境,并安装Pillow库。代码实现包括导入Pillow包和随机模块,定义随机生成字母、数字和字体颜色的函数。 ... [详细]
author-avatar
儒雅的aaaaaaaaaaa
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有