1. 程式人生 > >Python 類與物件

Python 類與物件

類與物件是面向物件程式設計的兩個主要方面。

#建立一個名叫 Person 的類
class Person:
    
    def __init__(self,name):
        self.name = name
        
    def say_hi(self):#def 方法
        print("my name is {}".format(self.name))
p = Person("jimmy") #給Person類建立一個物件p或例項p
p.say_hi()

(output:)my name is jimmy 

  • 1,2引數傳遞給方法.
  • 3 self引數指向當前例項自身.
  • 4 我們不需要傳遞例項自身給方法,Python直譯器自己會做這些操作的.

__init__方法

__init__方法會在類的物件被例項化時(p = Person("jimmy"))立即執行。這方法可以對任何你想進行操作的目標物件進行初始化操作。

self

類方法與普通函式的區別在於多了一個self名稱。當你呼叫功能時,Pyhton會自動為該引數賦值。

沒有引數的例項方法也必須擁有一個引數——self.

繼承

下面這段程式碼引用自《a byte of python》

class SchoolMember:
    """公用類,父型別"""
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print(('Initialized SchoolMember:{}').format(self.name))


    def tell(self):
        """tell me more"""
        print('name:"{}" Age:"{}"'.format(self.name, self.age),end = " ")


class Teacher(SchoolMember):#子型別
    """代表一個老師"""
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print('Initialized Teacher:{}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Salary:"{:d}"'.format(self.salary))


class Student(SchoolMember):#子型別
    """代表一個學生"""
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('Initialized Student:{}'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('marks:"{:d}"'.format(self.marks))


if __name__ == '__main__':
    t = Teacher('Mrs. Shrividya',40 ,30000)
    s = Student('XiaoMing', 20, 75 )
    print()
    members = [t,s]
    for member in members:
        member.tell()
output:        
Initialized SchoolMember:Mrs. Shrividya
Initialized Teacher:Mrs. Shrividya
Initialized SchoolMember:XiaoMing
Initialized Student:XiaoMing