2013-01-13 58 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