python基礎---->python的使用(六)

來源:互聯網
上載者:User

標籤:recent   state   instance   存在   繼承   mod   yield   over   info   

  這裡記錄一下python中關於class類的一些知識。不解釋就弄不懂的事,就意味著怎樣解釋也弄不懂。

 

python中的類知識一、class的屬性引用與執行個體
class MyClass():    ‘‘‘A simple exampel class‘‘‘    i = 12345 # class variable shared by all instances     def __init__(self, realpart, imagpart):        self.real = realpart # instance variable unique to each instance        self.imag = imagpart    def f(self):        return self.real + ‘hello‘x = MyClass(‘huhx‘, ‘linux‘)print(x.real, x.imag, x.i, MyClass.i)  # MyClass.real會報錯print(MyClass.__doc__, x.__doc__)  # A simple exampel classprint(MyClass.f(x), x.f())  # huhxhello huhxhello
  • When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.所以python類的__init__()方法類似於java中構造方法。
  • MyClass類的屬性i在所有MyClass的執行個體中共用,而real和imag就是執行個體私人,每個MyClass的執行個體這兩個屬性值可能是不一樣的。關於這個,請看下面的這個例子
 1 class Dog(): 2     tricks = [] 3  4     # def __init__(self): 5     #     self.tricks = [] 6  7     def add_tricks(self, trick): 8         self.tricks.append(trick) 9 d = Dog()10 d.add_tricks(‘roll over‘)11 e = Dog()12 e.add_tricks(‘play dead‘)13 print(d.tricks, e.tricks) # [‘roll over‘, ‘play dead‘] [‘roll over‘, ‘play dead‘]

如果注釋掉第二行,開啟4、5行。啟動並執行結果:[‘roll over‘] [‘play dead‘]。類的方法還可以定義在類的外面,測試案例如下:

def f1(self, x, y):    return min(x, y)class C():    f = f1    def g(self):        return ‘hello world‘    h = gclassC = C()print(C.f(classC, 2, 45), classC.f(2, 45)) # 2 2print(classC.h()) # hello worldclassC.h = ‘hello abc‘print(classC.g(), classC.h) # hello world hello abc

上述的例子可以看到f1定義在類C的外面,可以正常使用。而且在類中賦值h = g,修改h的值。不會影響到g,說明類中的方法賦值是值傳遞。

 

二、python類的繼承與存取權限

python的繼承文法如下,可以支援多層繼承。

class DerivedClassName(Base1, Base2, Base3):    <statement-1>    .    .    .    <statement-N>

 關於python的私人變數,提供下述的代碼:

class Student(object):    def __init__(self, name, score):        self.__name = name        self.__score = score        self._name = name    def print_score(self):        print(‘%s: %s‘ % (self.__name, self.__score))bart = Student(‘Bart Simpson‘, 59)# print(bart.__name) # AttributeError: ‘Student‘ object has no attribute ‘_name‘print(bart._Student__name)print(bart._name) # 約定是外部不能訪問,但是實際上外部可以訪問。print(type(bart)) # <class ‘__main__.Student‘>print(isinstance(bart, Student), issubclass(Student, object)) # True True

python中可以定義一個空的類,屬性和方法可以自行添加。

class Employee:    passjohn = Employee()  # Create an empty employee record# Fill the fields of the recordEmployee.name = ‘John Doe‘john.dept = ‘computer lab‘john.salary = 1000print(john.name) # John Doe

 

三、python類中的Generators與Iterators
# one wayfor ele in [1, 2, 3]:    print(ele, end=‘ ‘)print()# iters = ‘abc‘it = iter(s)print(next(it), next(it), next(it), end=‘ ‘)print()# Generatorsdef reverse(data):    for index in range(len(data)-1, -1, -1):        yield data[index]for char in reverse(‘huhx‘):    print(char, end=‘ ‘)print()# class next and iterclass Reverse:    """Iterator for looping over a sequence backwards."""    def __init__(self, data):        self.data = data        self.index = len(data)    def __iter__(self):        return self    def __next__(self):        if self.index == 0:            raise StopIteration        self.index = self.index - 1        return self.data[self.index]rev = Reverse(‘linux‘)for char in rev:    print(char, end=‘ ‘)# 1 2 3# a b c# x h u h# x u n i l

 

四、python類的一些特殊方法

  Python允許在定義class的時候,定義一個特殊的__slots__變數,來限制該class執行個體能添加的屬性:

class Student(object):    __slots__ = (‘name‘, ‘age‘)s = Student()s.name = ‘huhx‘s.age = 45s.score = 45

運行會報錯:

Traceback (most recent call last):  File "G:/Java/Go/program/2017-05-18/LearnPython1/test10/huhx5.py", line 8, in <module>    s.score = 45AttributeError: ‘Student‘ object has no attribute ‘score‘

  Python內建的@property裝飾器就是負責把一個方法變成屬性調用的。當調用不存在的屬性時,比如score,Python解譯器會試圖調用__getattr__(self, ‘score‘)來嘗試獲得屬性。__str__()方法類似於java類中的toString方法。如下案例

class Student(object):    @property    def score(self):        return ‘score = ‘ + str(self._score)    @score.setter    def score(self, value):        if not isinstance(value, int):            raise ValueError(‘score must be an integer!‘)        if value < 0 or value > 100:            raise ValueError(‘score must between 0 ~ 100!‘)        self._score = value    def __str__(self):        return ‘student info: ‘ + self.score    def __getattr__(self, item):        if item == ‘address‘:            return ‘china‘        elif item == ‘attr_fun‘:            return lambda x: x * xs = Student()s.score = 60print(s.score) # score = 60print(s.address) # chinaprint(s.attr_fun(4)) # 16print(s) # student info: score = 60s.score = 999 # 拋出異常

 

友情連結

 

python基礎---->python的使用(六)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.