標籤:each object obj hat swa 類變數 method 自己 repr
11、物件導向的編程
(1)簡介
略
(2)self
假如你有一個類稱為MyClass和這個類的一個執行個體MyObject。
當你調用這個對象的方法MyObject.method(arg1, arg2)的時候,
這會由Python自動轉為MyClass.method(MyObject, arg1, arg2)——這就是self的原理了。
(3)類
略
(4)對象的方法
略
(5)__init__方法
略
(6)類與對象的變數
類的變數 由一個類的所有對象(執行個體)共用使用。只有一個類變數的拷貝,所以當某個對象對類的變數做了改動的時候,這個改動會反映到所有其他的執行個體上。
對象的變數 由類的每個對象/執行個體擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共用的,在同一個類的不同執行個體中,雖然對象的變數有相同的名稱,但是是互不相關的。
1 # coding=utf-8 2 class Person(object): 3 """Represents a person.""" 4 population = 0 # 類變數 5 6 def __init__(self, name): 7 """Initializes the person‘s data.""" 8 self.name = name # 執行個體變數 9 print "(Initializing %s)" % self.name10 11 # When this person is created, he/she12 # adds to the population13 Person.population += 114 15 def __del__(self):16 """I am dying."""17 print "%s says bye." % self.name18 19 Person.population -= 120 21 if Person.population == 0:22 print "I am the last one."23 else:24 print "There are still %d people left." % Person.population25 26 def say_hi(self):27 """Greeting by the person.28 29 Really, that‘s all it does."""30 print "Hi, my name is %s." % self.name31 32 def how_many(self):33 """Prints the current population."""34 if Person.population == 1:35 print "I am the only person here."36 else:37 print "We havve %d persons here." % Person.population38 39 40 if __name__ == "__main__":41 print "*" * 20 + "Swaroop Begin" + "*" * 2042 swaroop = Person("Swaroop")43 swaroop.say_hi()44 swaroop.how_many()45 46 print "*" * 20 + "Kalam Begin" + "*" * 2047 kalam = Person("Abdul Kalam")48 kalam.say_hi()49 kalam.how_many()50 51 print "*" * 20 + "say_hi && how_many" + "*" * 2052 swaroop.say_hi()53 swaroop.how_many()54 55 print "*" * 20 + "End" + "*" * 20對象方法
輸出:
(7)繼承
1 # -*- coding:utf-8 -*- 2 3 4 class SchoolMember(object): 5 """Represents any school member.""" 6 7 def __init__(self, name, age): 8 self.name = name 9 self.age = age10 print "(Initialized SchoolMember:%s)" % self.name11 12 def tell(self):13 """Tell my details."""14 print "Name:\"%s\" Age:\"%s\"" % (self.name, self.age)15 16 17 class Teacher(SchoolMember):18 """Represents a teacher."""19 20 def __init__(self, name, age, salary):21 SchoolMember.__init__(self, name, age) # 調用父類的初始化22 self.salary = salary23 print "(Initialized Teacher:%s" % self.name24 25 def tell(self):26 SchoolMember.tell(self) # 通過類調用父類的方法,不需要建立對象27 print "Salary:\"%d\"" % self.salary28 29 30 class Student(SchoolMember):31 """Represents a student."""32 33 def __init__(self, name, age, marks):34 SchoolMember.__init__(self, name, age)35 self.marks = marks36 print "(Initialized Student:%s)" % self.name37 38 def tell(self):39 SchoolMember.tell(self)40 print "Marks:\"%d\"" % self.marks41 42 43 if __name__ == "__main__":44 print "**" * 20 + "Teacher" + "**" * 2045 t = Teacher("Mrs.Shrividya", 40, 30000)46 47 print "**" * 20 + "Student" + "**" * 2048 s = Student("Swaroop", 22, 75)49 50 print "**" * 4451 members = [t, s]52 for member in members:53 member.tell()繼承
輸出:
簡明Python教程學習筆記7