[英]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);
}
}
直接翻譯此代碼將浪費時間。 從Java遷移到Python時,最困難的事情是放棄大多數您所知道的東西。 但是簡單的事實是Python不是Java ,並且逐行翻譯將無法按您期望的那樣工作。 最好翻譯算法而不是代碼,而讓Python做自己擅長的事情。
我不清楚您的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類一樣。 我試圖在此處的示例中進行說明。
這不是逐行翻譯,而是在球場上:
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/包含有關此主題的大量幫助。 請注意,深度拷貝支持可能不適用於它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.