我有 this question之前贴过,但不是很清楚,我也很难找到答案。由于我对其进行了编辑以使其更有意义,因此人们似乎没有看过它,也许是因为他们看到它已经有 6 个答案。所以我重新=-张贴在这里:
总的来说,我对 Python 和编程还是个新手,所以我需要简单的解释!我什至不知道你说的字典是什么东西!
我正在尝试为我的妹妹制作一款游戏。这是一种虚拟宠物之类的东西,宠物有玩具可以玩。
我创建了一个类 Toy
并想创建一个函数 getNewToy(name, data1, data2, data3, data4, data5)
。
我希望此函数创建类 Toy
的新实例,并且我希望每次创建新实例时都能调用该函数多次。
根据我的经验,您可以创建一个实例:
class Toy:
def __init__(self, name, data1, data2, data3, data4, data5):
pass
myToy = Toy(myToy, 1, 2, 3, 4, 5)
然后使用类中的方法:
myToy.method1()
既然我想拥有多个玩具,每个玩具都有一个 playWith()
方法,我希望实例每次都能反射(reflect) Toy
的名称一个被称为。
我希望每次调用方法 getNewToy(,...)
时实例都不同,并且实例可以反射(reflect)名称。
请记住,我是编程新手,所以你能不能让解释简单点。
非常感谢,现在更容易理解了!
最佳答案
以下是我将如何按照您的说明进行操作:
# The following two classes are toys, both have a playWith
# as you wanted, each playWith do different things
class Ball:
def __init__(self):
self.name = "ball"
def playWith(self):
print "the ball bounces"
class Car:
def __init__(self):
self.name = "car"
def playWith(self):
print "the car is fast"
# This is a Python generator, every time .next() is called on it,
# the next "yield-value" is returned
def generator():
while True:
yield Ball()
yield Car()
# This is the creator, it has to be a class rather than a function
# since you wanted a new toy each time getNewToy is called
# and as such the generator needs to be tracked
class ToyCreator:
def __init__(self):
self.generator = generator()
def getNewToy(self):
return self.generator.next()
# Create five toys, print their name and play with them
# Do note here that even though we ask for five toys but only have
# two "yields" in the generator, the generator "wraps around" (since,
# internally, its just an endless loop)
toyCreator = ToyCreator()
for i in range(5):
toy = toyCreator.getNewToy()
print "Toy",i,toy.name,"\t:",
toy.playWith()
如果您无法理解 yield 业务,请查看documentation for the python generator .
你要做的是实现一个 design pattern , 一个 factory pattern , 更准确地说。
还在迷茫吗?再读一遍,想一想,但不要犹豫,问。我们是来帮忙的。 :)
关于python - 在 Python 中使用变量创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2138027/