Python物件導向高階程式設計 slot

2022-03-08 21:26:09 字數 1296 閱讀 5205

綱要:

本章總的來說是給例項新增屬性,給類新增方法兩個主題,以及相應的作用範圍。總結如下:

1.給例項新增屬性(作用範圍:當然是只對當前例項有效);

2.用__slots__限制可以給例項新增的屬性(作用範圍:__slots__定義的屬性僅對當前類例項起作用,對繼承的子類是不起作用的,除非在子類中也定義__slots__);

3.用types模組中的methodtype方法給例項新增方法;(作用範圍:給「例項…」當然是限制於本例項);

4.給類新增方法;(作用範圍:對所有例項生效)

以下是**部分,邏輯較亂,但是都是上述四點的證據:

1 #!/usr/bin/env python

2 # -*- coding:utf-8 -*-

3class student(object):

4 __slots__ = ('name','age')#限制給類新增的屬性

5def set_score(self,score):

6 self.score = score

7 s = student()

8 from types

import

methodtype

9 s.set_setscore = methodtype(set_score,s)#給例項新增方法

10 s.set_setscore(100)

11print(s.score)

12 s.name = 'bolen'

13 s.age = 18

14 s.tt = 'test' #限制屬性裡只有name和score,所以此次會報錯"has no attribute..."

15 print(s.name,s.age,s.tt)

16 s2 = student() #給乙個例項新增方法,對另乙個例項是不起作用的

17 student.set_score = set_score #為了給所有例項都新增方法,可以給類新增方法。

1819 #使用__slots__要注意,__slots__定義的屬性僅對當前類例項起作用,對繼承的子類是不起作用的:

20class graduatestudent(student):

21 pass

2223 g = graduatestudent()

24 g.tt = 9999

25 #除非在子類中也定義__slots__,這樣,子類例項允許定義的屬性就是自身的__slots__加上父類的__slots__。

python3中的__slots__

python 物件導向高階程式設計

python 裝飾器 property使用 classscreen property defwidth self returnself.width pass width.setter defwidth self,value self.width value property defheight se...

python物件導向高階程式設計

1.繫結方法 給所有例項都繫結方法,可以給class繫結方法 def set score self,score self.score score student.set score set score 給class繫結方法後,所有例項均可呼叫。但是,如果我們想要限制例項的屬性怎麼辦?比如,只允許對s...

物件導向高階程式設計

相同class的各物件互為友元 class complex int func const complex param private double re,im string inline string string const char cstr 0 else inline string strin...