C#のクラスとオブジェクトの違いは何ですか?
クラスを定義するときは、データ型の青写真を定義します。
オブジェクトはクラスのインスタンスです。クラスを構成するメソッドと変数は、クラスのメンバーと呼ばれます。
クラスメンバーにアクセスするには、オブジェクト名の後にドット(。)演算子を使用します。ドット演算子は、オブジェクトの名前をメンバーの名前にリンクします。たとえば、
Box Box1 = new Box();
上に、Box1がオブジェクトであることがわかります。メンバーにアクセスするために使用します-
Box1.height = 7.0;
メンバー関数を呼び出すためにも使用できます-
Box1.getVolume();
以下は、C#でオブジェクトとクラスがどのように機能するかを示す例です-
例
using System;
namespace BoxApplication {
class Box {
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len ) {
length = len;
}
public void setBreadth( double bre ) {
breadth = bre;
}
public void setHeight( double hei ) {
height = hei;
}
public double getVolume() {
return length * breadth * height;
}
}
class Boxtester {
static void Main(string[] args) {
// Creating two objects
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// using objects to call the member functions
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
} 出力
Volume of Box1 : 210 Volume of Box2 : 1560
-
Pythonの古いスタイルと新しいスタイルのクラスの違いは何ですか?
Python 2.xには、基本クラスとしての組み込み型の有無に応じて、2つのスタイルのクラスがあります- "classic" style or old style classes have no built-in type as a base class: >>> class OldSpam: # no base class ... pass >>> OldSpam.__bases__ () 「新しい」スタイルクラス:基本クラスとして組み込み型があります。つまり、直接的ま
-
Pythonの__str__と__repr__の違いは何ですか?
組み込み関数repr()およびstr()は、それぞれobject .__ repr __(self)およびobject .__ str __(self)メソッドを呼び出します。最初の関数はオブジェクトの公式表現を計算し、2番目の関数はオブジェクトの非公式表現を返します。 両方の関数の結果は、整数オブジェクトでも同じです。 >>> x = 1 >>> repr(x) 1 >>> str(x) 1 ただし、文字列オブジェクトには当てはまりません。 >>> x = Hello >>> repr(x)