pythonクラスとクラスのプロパティへのアクセス方法
9595 ワード
クラスの作成(Class):同じ属性とメソッドを持つオブジェクトの集合を記述します.コレクション内の各オブジェクトに共通するプロパティとメソッドを定義します.オブジェクトはクラスのインスタンスです.class文を使用して新しいクラスを作成します.classの後にクラスの名前を付け、次の例でコロンで終わります.
次のコードはEmployeeというクラスを作成します.
次のコードは、Employeeのインスタンスを作成します.
アクセス属性はポイント(.)を使用できます.に表示されます.次のクラス名を使用してクラス変数にアクセスします.
クラスのプロパティを変更したり、追加したり、削除したりすることもできます.
クラスの継承
オブジェクト向けのプログラミングがもたらす主な利点の1つはコードの再利用であり,この再利用を実現する方法の1つは継承メカニズムによるものである.継承はクラス間のタイプとサブタイプの関係として完全に理解できます.継承構文はclass派生クラス名(ベースクラス名)://...ベースクラス名はカッコで記述され、基本クラスはクラス定義時にメタグループに指定されます.派生クラスの宣言は、親クラスと同様に、継承されたベースクラスのリストがクラス名の後に続き、次のようになります.
以下に継承する例を示します.
メソッド書き換え
親メソッドの機能があなたのニーズを満たすことができない場合は、子メソッドで親メソッドを書き換えることができます.
転載先:https://www.cnblogs.com/lely/p/10175123.html
class ClassName:
' ' #
class_suite #
次のコードはEmployeeというクラスを作成します.
class Employee:
# ' '
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
次のコードは、Employeeのインスタンスを作成します.
# " Employee "
emp1 = Employee("Zara", 2000)
# " Employee "
emp2 = Employee("Manni", 5000)
アクセス属性はポイント(.)を使用できます.に表示されます.次のクラス名を使用してクラス変数にアクセスします.
#
class Employee:
# ' '
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
# " Employee "
emp1 = Employee("Zara", 2000)
# " Employee "
emp2 = Employee("Manni", 5000)
#
emp1.displayEmployee()
emp2.displayEmployee()
クラスのプロパティを変更したり、追加したり、削除したりすることもできます.
emp1.age = 7 # 'age'
emp1.age = 8 # 'age'
del emp1.age # 'age'
クラスの継承
オブジェクト向けのプログラミングがもたらす主な利点の1つはコードの再利用であり,この再利用を実現する方法の1つは継承メカニズムによるものである.継承はクラス間のタイプとサブタイプの関係として完全に理解できます.継承構文はclass派生クラス名(ベースクラス名)://...ベースクラス名はカッコで記述され、基本クラスはクラス定義時にメタグループに指定されます.派生クラスの宣言は、親クラスと同様に、継承されたベースクラスのリストがクラス名の後に続き、次のようになります.
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
以下に継承する例を示します.
class Parent: #
parentAttr = 100
def __init__(self):
print " "
def parentMethod(self):
print ' '
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print " :", Parent.parentAttr
class Child(Parent): #
def __init__(self):
print " "
def childMethod(self):
print ' child method'
c = Child() #
c.childMethod() #
c.parentMethod() #
c.setAttr(200) #
c.getAttr() #
メソッド書き換え
親メソッドの機能があなたのニーズを満たすことができない場合は、子メソッドで親メソッドを書き換えることができます.
class Parent: #
def myMethod(self):
print ' '
class Child(Parent): #
def myMethod(self):
print ' '
c = Child() #
c.myMethod() #
転載先:https://www.cnblogs.com/lely/p/10175123.html