python-6物件導向編程

來源:互聯網
上載者:User

標籤:abc   range   int   and   調用   獲得   方便   pre   lam   

1-類和執行個體

class Student(object):    def __init__(self, name, score):# _init__方法的第一個參數永遠是self,表示建立的執行個體本身        self.name = name        self.score = score    def print_score(self):        print(‘nams:%s, score:%s‘%(self.name,self.score))    def get_grade(self):        if(self.score >=90):            return ‘A‘        elif(self.score >= 60):            return ‘B‘        else:            return ‘C‘#調用   stu = Student(‘qinzhongbao‘,79)stu.print_score()print(stu.get_grade())

2-訪問限制
  例的變數名如果以__開頭,就變成了一個私人變數(private),只有內部可以訪問

class Person(object):    def __init__(self, name, score):        self.__name = name        self.__score =score    def print_score(self):        print(‘name:%s,score:%s‘%(self.__name,self.__score))    def get_name(self):        return self.__name    person = Person(‘fengyong‘,88)person.__name =‘newName‘ #修改值print(person.__name) #newNameprint(person.get_name()) #fengyong 修改值沒有生效

3-繼承和多態

class Animal(object): #繼承object    def run(self):        print(‘Animal is running‘)        class Dog(Animal): #繼承Animal    def run(self):        print(‘Dog is running‘)        class Cat(Animal):    def run(self):        print(‘Cat is running‘)        def run(animail):     animail.run()     animal = Animal()run(animal)    run(Dog())run(Cat())#對於Python這樣的動態語言來說,則不一定需要傳入Animal類型。#我們只需要保證傳入的對象有一個run()方法就可以了

 4-擷取對象資訊

  4.1使用type()函數

type(123)#<class ‘int‘>type(‘str‘) #<class ‘str‘>type(123)==type(456) #Truetype(‘abc‘)==str #Truetype(‘abc‘)==type(123) #Falseimport types def fn():    passtype(fn)==types.FunctionType#Truetype(abs)==types.BuiltinFunctionType #Truetype(lambda x: x)==types.LambdaType#Truetype((x for x in range(10)))==types.GeneratorType #Truedir(types)  #可查看types常用常量

   4.2 isinstance使用

#使用 isinstance, 對於class繼承來說,type()就很不方便#如果繼承關係是:object -> Animal -> Dog -> Huskyisinstance(d, Dog) and isinstance(d, Animal) #trueisinstance([1, 2, 3], (list, tuple)) #判斷是某類型中的一種isinstance(b‘a‘, bytes) #True

  4.3 dir使用

#如果要獲得一個對象的所有屬性和方法,可以使用dir()函數,它返回一個包含字串的listdir(‘ABC‘)

 4.4 len(obj)

  我們自己寫的類,如果也想用len(myObj)的話,就自己寫一個__len__()方法

4.5 getattr()、setattr()以及hasattr()

  僅僅把屬性和方法列出來是不夠的,配合getattr()、setattr()以及hasattr(),我們可以直接操作一個對象的狀態:

class MyObject(object):     def __init__(self):         self.x = 9     def power(self):        return self.x * self.xobj = MyObject()hasattr(obj, ‘x‘) # 有屬性‘x‘嗎? Truesetattr(obj, ‘y‘, 19) # 設定一個屬性‘y‘  getattr(obj, ‘y‘) # 擷取屬性‘y‘,如果不存在此屬性會報異常getattr(obj, ‘z‘, 404) # 擷取屬性‘z‘,如果不存在,返回預設值404,
   執行個體屬性和類屬性
class Student(object):    name =‘fengyong‘ #類的屬性    stu = Student()stu.name #fengyongstu.name = ‘new Name‘stu.name #new Namedel(stu.name) #刪除綁定的屬性stu.name #fengyong 類屬性的值

從上面的例子可以看出,在編寫程式的時候,千萬不要對執行個體屬性和類屬性使用相同的名字,因為相同名稱的執行個體屬性將屏蔽掉類屬性,但是當你刪除執行個體屬性後,再使用相同的名稱,訪問到的將是類屬性

python-6物件導向編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.