有没有将Java中的以下代码转换为Python的等价?
public class Animal{
public enum AnimalBreed{
Dog, Cat, Cow, Chicken, Elephant
}
private static final int Animals = AnimalBreed.Dog.ordinal();
private static final String[] myAnimal = new String[Animals];
private static Animal[] animal = new Animal[Animals];
public static final Animal DogAnimal = new Animal(AnimalBreed.Dog, "woff");
public static final Animal CatAnimal = new Animal(AnimalBreed.Cat, "meow");
private AnimalBreed breed;
public static Animal myDog (String name) {
return new Animal(AnimalBreed.Dog, name);
}
}
答案 0 :(得分:7)
直接翻译此代码会浪费时间。从Java迁移到Python时最难的事情是放弃你所知道的大部分内容。但简单的事实是Python is not Java,逐行翻译将无法按预期工作。最好是翻译算法而不是代码,让Python做它擅长的事情。
答案 1 :(得分:2)
我不清楚Java所需的语义是什么。我猜你有点试图模拟一组动物(物种,而不是品种,偶然),并灌输一组相关的类,其行为根据动物的类型而变化(粗略地说每个动物的声音) )。
在Python中,自然的方法是通过元编程。您可以创建一个类或工厂函数,通过将参数传递给模板来返回每个类。由于函数和类是Python中的一阶对象,因此它们可以像任何其他对象一样传递。由于类本身就是对象,因此您可以使用setattr
(及其堂兄:hasattr
和getattr
)来访问其属性。
这是一个简单的例子:
#!/usr/bin/env python
def Animal(species, sound):
class meta: pass
def makeSound(meta, sound=sound):
print sound
setattr(meta, makeSound.__name__, makeSound)
def name(meta, myname=species):
return myname
setattr(meta, 'name', name)
return meta
if __name__ == '__main__':
animal_sounds = (('Dog', 'woof'),
('Cat', 'meow'),
('Cow', 'moo'),
('Chicken', 'cluck'),
('Elephant', 'eraunngh'))
menagerie = dict()
for animal, sound in animal_sounds:
menagerie[animal] = Animal(animal, sound)
for Beast in menagerie:
beast = Beast()
print beast.name(), ' says ',
beast.makeSound()
Dog = menagerie['Dog']
fido = Dog() # equivalent to fido = menagerie['Dog']()
fido.makeSound()
# prints "woof"
Cat = menagerie['Cat']
felix = Cat()
felix.makeSound()
Mouse = Animal('Mouse', 'squeak')
mickey = Mouse()
mouse.makeSound()
# prints "squeak"
这似乎是一个陈腐的例子,但我希望它能说明问题。我可以创建一个表(在本例中是一个元组元组),它提供了用于填充类的变化参数/行为的参数。 Animal返回的类与任何其他Python类一样。我试图在这里的例子中表明这一点。
答案 2 :(得分:1)
这不是逐行转换,而是大概的事情:
class Animal(object):
animal_breeds = "Dog Cat Cow Chicken Elephant".split()
animals = {}
def __init__(self, breed, name):
self._breed = breed
self.name = name
Animal.animals[name] = self
@property
def breed(self):
return Animal.animal_breeds[self._breed]
@staticmethod
def myDog(name):
return Animal(Animal.AnimalBreed.Dog, name)
# add enumeration of Animal breeds to Animal class
class Constants(object): pass
Animal.AnimalBreed = Constants()
for i,b in enumerate(Animal.animal_breeds):
setattr(Animal.AnimalBreed, b, i)
# define some class-level constant animals
# (although "woff" and "meow" are not what I would expect
# for names of animals)
Animal.DogAnimal = Animal(Animal.AnimalBreed.Dog, "woff")
Animal.CatAnimal = Animal(Animal.AnimalBreed.Cat, "meow")
# this code would be in a separate module that would import this
# code using
# from animal import Animal
#
print Animal.myDog("Rex").breed
print Animal.animals.keys()
答案 3 :(得分:0)
http://code.activestate.com/recipes/413486/包含有关此主题的大量帮助。请注意,深度支持可能不适用于它。