简体   繁体   English

Python的等效性?

[英]Python's equivalence?

Is there anyway to transform the following code in Java to Python's equivalence? 无论如何,是否可以将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);

      }
}

Translating this code directly would be a waste of time. 直接翻译此代码将浪费时间。 The hardest thing when moving from Java to Python is giving up most of what you know. 从Java迁移到Python时,最困难的事情是放弃大多数您所知道的东西。 But the simple fact is that Python is not Java , and translating line by line won't work as you expect. 但是简单的事实是Python不是Java ,并且逐行翻译将无法按您期望的那样工作。 It's better to translate algorithms rather than code, and let Python do what it's good at. 最好翻译算法而不是代码,而让Python做自己擅长的事情。

It's unclear to me what the desired semantics of your Java would be. 我不清楚您的Java期望的语义是什么。 I'm guessing you're sort of trying to model a collection of animals (species, not breeds, incidentally) and imbue a set of associated classes with the behavior that varies according to the type of animal (roughly speaking the sounds that each makes). 我猜您是在尝试对动物(物种,而非品种)的集合进行建模,并使一组相关类的行为因动物类型而异(大致来说,每种动物发出的声音)。

In Python the natural way to do this would be through meta programming. 在Python中,执行此操作的自然方法是通过元编程。 You create a class or a factory function which returns each of the classes by passing arguments into a template. 您创建一个类或工厂函数,该函数通过将参数传递到模板中来返回每个类。 Since functions and classes are first order object in Python they can be passed around like any other object. 由于函数和类是Python中的一阶对象,因此可以像其他任何对象一样传递它们。 Since classes are themselves objects you can access their attributes using setattr (and its cousins: hasattr and getattr ). 由于类本身是对象,因此您可以使用setattr (及其表亲hasattrgetattr )访问其属性。

Here's a simple example: 这是一个简单的例子:

#!/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"

This seems like a trite example but I hope it gets the point across. 这似乎是一个过时的例子,但我希望它能阐明这一点。 I can create a table (in this case a tuple of tuples) which provides the arguments which will be used to fill in the varying parameters/behavior of our classes. 我可以创建一个表(在本例中为元组的元组),该表提供用于填充类的各种参数/行为的参数。 The classes returned by Animal are just like any other Python classes. Animal返回的类与其他任何Python类一样。 I've tried to show that in the examples here. 我试图在此处的示例中进行说明。

This is not a line-for-line translation, but something in the ballpark: 这不是逐行翻译,而是在球场上:

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()

http://code.activestate.com/recipes/413486/ contains a lot of help on this topic. http://code.activestate.com/recipes/413486/包含有关此主题的大量帮助。 Be warned that deepcopy support probably doesn't work with it. 请注意,深度拷贝支持可能不适用于它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM