2017-08-08 7 views
1

Javascriptのコンストラクタ+オブジェクトの例を作成Javascriptを `this` Pythonの` self`コンストラクタ対

//Constructor 
function Course(title,instructor,level,published,views){ 
    this.title = title; 
    this.instructor = instructor; 
    this.level = level; 
    this.published = published; 
    this.views = views; 
    this.updateViews = function() { 
     return ++this.views; 
    } 
} 

//Create Objects 
var a = new Course("A title", "A instructor", 1, true, 0); 
var b = new Course("B title", "B instructor", 1, true, 123456); 

//Log out objects properties and methods 
console.log(a.title); // "A Title" 
console.log(b.updateViews()); // "123457" 

このPythonの同等は何ですか? (コンストラクタ関数/またはクラス+プロパティ&メソッドをログアウト+オブジェクトのインスタンスを作成します?)

はJavaScriptからのpythonからselfthisの間に違いはありますか?ここで

+3

かなり、違いはありません。 Pythonでは、 'self'は慣習であり、あなたはそれをあなたが望むものと呼ぶことができます。また、JSをコンストラクタの最初のパラメータとして含める必要がありますが、JSは "本能的に"これが何であるかを知っています – inspectorG4dget

+0

[クラスに関するPythonのドキュメント](https://docs.python.org/3 /tutorial/classes.html)? –

+0

あなたの質問には、用語の切り替えがあります – Mangohero1

答えて

2

はPythonの翻訳です:

class Course: 

    def __init__(self,title,instructor,level,published,views) 

     self.title = title 
     self.instructor = instructor 
     self.level = level 
     self.published = published 
     self.views = views 

    def update_views(self): 
     return self.views += 1 

あなたは次のようにそのクラスを初期化し、その後、クラスを宣言する必要があります。

course = Course("title","instructor","level","published",0) 

いくつかの顕著な違いは、自己が実際に暗黙的に利用できないが、ということですクラスのすべてのインスタンス関数に必要なパラメータ。ただし、詳細については、 the documentationにpythonクラスを問い合わせてください。

+0

だから、Pythonではクラスの中でプロパティ/メソッドを別々に(defで)定義しなければなりませんか? – Kagerjay

+2

@Kagerjay huh?基本的に、PythonとJavascriptは異なるOOPモデルを持っています。 Javascriptはプロトタイプベースの継承を使用しますが、Pythonはクラスベースの継承を使用します。私はクラスがECM6に導入されたと信じています。 Pythonのインスタンスにコンストラクタで関数のプロパティを動的に追加することはできますが、継承されることはありません。 –

+0

私は情報のためのいくつかのより多くの読書のおかげを行う必要があります:) – Kagerjay

0

print(courseB.update_views)出力し、このかかわらを使用

#Constructors 
class Course: 

    def __init__(self,title,instructor,level,published,views): 

     self.propTitle = title 
     self.propInstructor = instructor 
     self.propLevel = level 
     self.propPublished = published 
     self.propViews = views 

    def update_views(self): 
     self.propViews += 1 
     return self.propViews 

# Create objects 
courseA = Course("A title", "A instructor", 1, True, 0) 
courseB = Course("B title", "B instructor", 1, True, 123456) 

# Print object property and use object method 
print(courseA.propTitle) 
print(courseB.update_views()) 

結果のプリントアウト

タイトル

今それを修正Pythonのソリューションにより多少の誤差があったが、 <bound method Course.update_views of <__main__.Course object at 0x7f9f79978908>>、u se print(courseB.update_views())

+1

これは 'courseB.update_views()'のようにuse()するだけです。 – Igor

+1

@Igorが正しいです。メソッドを呼び出す必要があります。それはコンピュータの財産ではありません。 – modesitt

+0

大丈夫私は今それを固定しました、私はすべての名前を 'prop'接頭語と名づけました。 – Kagerjay

関連する問題