2013-01-13 59 views
0

我想将下面的Java代码片段转换为Python。有人能帮我解决这个问题吗?我是Python的新手。在Python中实现Java对象创建

Java代码:

public class Person 
{ 
public static Random r = new Random(); 
public static final int numFriends = 5; 
public static final int numPeople = 100000; 
public static final double probInfection = 0.3; 
public static int numInfected = 0; 

/* Multiple experiments will be conducted the average used to 
    compute the expected percentage of people who are infected. */ 
private static final int numExperiments = 1000; 

/* friends of this Person object */ 
private Person[] friend = new Person[numFriends]; ----- NEED TO REPLICATE THIS IN PYTHON 
private boolean infected; 
private int id; 

我试图复制在上面的标记线成Python同样的想法。有人可以转换“私人人物[]朋友=新人[numFriends];”实现成python。我正在寻找一个代码片段...谢谢

+1

你的问题是什么?这是一个问答网站。 – 2013-01-13 20:15:13

+0

你能告诉我什么是java代码中标记行的Python中声明的等效语法。 – CarbonD1225

回答

1

对我来说,你想知道,在Python中等效于一个固定长度的数组是什么。哪有这回事。你不必,也不能像这样预先分配内存。相反,只需使用一个空的列表对象。

class Person(object): 
    def __init__(self, name): 
     self.name = name 
     self.friends = [] 

然后使用它是这样的:

person = Person("Walter") 
person.friends.append(Person("Suzie"))  # add a friend 
person.friends.pop(0)      # remove and get first friend, friends is now empty 
person.friends.index(Person("Barbara"))  # -1, Barbara is not one of Walter's friends 

它的工作原理基本上和Java中的列表< T>。

哦,并且Python中没有访问修饰符(私有,公共等)。一切都是公开的,可以这么说。

+0

事实上,在Java中,它只为指针预先分配空间,所以Java在Java中的好处主要是便于下标语法。 – Marcin